设置导航栏渐变关键亮点第一navigationController.navigationBar.translucent = YES;第二设置navigationController.navigationBar的背景图片,导航栏的透明度渐变其实就是背景图透明度的渐变。
我们平时应用时,导航栏渐变同时也会改变状态栏颜色和导航栏上文字和图标的颜色。
关键代码
/**
注意,要在控制器里设置导航栏状态需要先在Info.plist设置View controller-based status bar appearance 为YES,
在有导航栏的页面,一定要设置导航栏控制器preferredStatusBarStyle由visibleViewController即他的子控制决定(见BaseNavigationController),
然后在子控制起设置preferredStatusBarStyle
*/
- (UIStatusBarStyle)preferredStatusBarStyle {
if (self.navBarAlpha > 0.8) {
return UIStatusBarStyleLightContent;
}
return UIStatusBarStyleDefault;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat offset = scrollView.contentOffset.y;
CGFloat alpha = offset / 40;
self.navBarAlpha = alpha;
NSLog(@"y轴偏移量:%f*******透明度:%f",offset,alpha);
//这儿imageWithColor方法为自定义color转image
[self.navigationController.navigationBar setBackgroundImage:[Tools imageWithColor:[UIColor colorWithRed:246/255.0 green:18/255.0 blue:56/255.0 alpha:alpha] size:CGSizeMake(1, 1)] forBarMetrics:UIBarMetricsDefault];
if (alpha > 0.8) {
[self setLightStyle];
} else {
[self setBlackStyle];
}
[self setNeedsStatusBarAppearanceUpdate];//更新状态栏
}
- (void)setBlackStyle {
self.rightBarBtnItem.image = [[UIImage imageNamed:@"buycarblack"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};
self.navigationController.navigationBar.translucent = YES;
}
- (void)setLightStyle {
self.rightBarBtnItem.image = [[UIImage imageNamed:@"buycarwhite"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};
self.navigationController.navigationBar.translucent = NO;//这儿设置为NO是为了保证导航栏一点不透明,视觉不看到下一层
}
特别要注意的是当导航栏背景图透明度为1.0时,若是不设置navigationController.navigationBar.translucent = NO,这时导航栏其实处于半透明的,看得到下面的图层,这儿可以根据实际需要设置,当设置为NO时,一定要记得在viewDidload中设置self.extendedLayoutIncludesOpaqueBars = YES,YES是为了保证设置导航栏translucent为NO时self.view的起点依然为(0, 0),否则会变为(0,状态栏高度+导航栏高度);出现跳动。
具体实现可以下载demo查看