1.功能需求
剛進入頁面導覽列背景為透明色,上劃一定距離改變導覽列顔色為白色(漸變)
2.功能實作
2.1 在viewWillAppera中實作導覽列背景色透明
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// 讓控件從(0,0)開始
self.navigationController.navigationBar.translucent = YES;
self.navigationController.navigationBar.shadowImage = [UIImage new];
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:0];
}
2.2 在scrollView代理方法 scrollViewDidScroll中實作随着滾動改變導航欄顔色透明度
//隻要滾動了就會觸發
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;{
// 動态更新navigationBar的顔色
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY > NAVBAR_CHANGE_POINT) {
CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + NavigationHeight - offsetY) / NavigationHeight));
[self.navigationController.navigationBar setBackgroundImage:[FFCommonView createImageWithColor:[Color_NavigationBar colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
if (alpha == 1) {
self.navigationController.navigationBar.translucent = NO;
}else{
self.navigationController.navigationBar.translucent = YES;
}
} else {
[self.navigationController.navigationBar setBackgroundImage:[FFCommonView createImageWithColor:[Color_NavigationBar colorWithAlphaComponent:0]] forBarMetrics:UIBarMetricsDefault];
}
}
ps:
Navbar_change_point為導覽列開始漸變色的距離;透明度變為1的時候設定translucent屬性為NO
2.3 在viewWillDeillDisappear中還原之間的一些設定
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
self.navigationController.navigationBar.translucent = NO;
//界面離開的時候重新設定回原來的樣式
[self.navigationController.navigationBar setBackgroundImage:[FFCommonView createImageWithColor:Color_NavigationBar] forBarMetrics:UIBarMetricsDefault];
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISO1cjMwYTM0ETMxYDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)