設置導航欄漸變關鍵亮點第一navigationController.navigationBar.translucent = YES;第二設置navigationController.navigationBar的背景圖片,導航欄的透明度漸變其實就是背景圖透明度的漸變。

Jun-21-2021 11-31-56.gif
我們平時應用時,導航欄漸變同時也會改變狀態(tài)欄顏色和導航欄上文字和圖標的顏色。
關鍵代碼
/**
注意,要在控制器里設置導航欄狀態(tài)需要先在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轉(zhuǎn)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];//更新狀態(tài)欄
}
- (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,這時導航欄其實處于半透明的,看得到下面的圖層,這兒可以根據(jù)實際需要設置,當設置為NO時,一定要記得在viewDidload中設置self.extendedLayoutIncludesOpaqueBars = YES,YES是為了保證設置導航欄translucent為NO時self.view的起點依然為(0, 0),否則會變?yōu)?0,狀態(tài)欄高度+導航欄高度);出現(xiàn)跳動。
具體實現(xiàn)可以下載demo查看