由于项目需求需要做到导航栏随tableView的滚动由透明到显示颜色。
所以在此做个笔记。
- (void)viewWillAppear:(BOOL)animated
{
//去掉透明后导航栏下边的黑边
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
UIImage *image = [self createAImageWithColor:[UIColor clearColor] alpha:0.0];
//设置导航栏背景图片为一个空的image,这样就透明了
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}
- (UIImage *)createAImageWithColor:(UIColor *)color alpha:(CGFloat)alpha{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextSetAlpha(context, alpha);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
tableView滚动时渐变导航栏颜色
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat minAlphaOffset = - 64;
CGFloat maxAlphaOffset = 200;
CGFloat offset = scrollView.contentOffset.y;
CGFloat alpha = (offset - minAlphaOffset) / (maxAlphaOffset - minAlphaOffset);
UIImage *image = [self createAImageWithColor:[UIColor orangeColor] alpha:alpha];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
NSLog(@"alpha %f",alpha);
}
到这里基本已经实现,不过当你需要push到其他页面的时候需要设置回来
视图即将消失的时候
- (void)viewWillDisappear:(BOOL)animated
{
self.navigationController.navigationBar.shadowImage = nil;
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
The End!