直接上代碼:
- (void)viewDidLoad {
[super viewDidLoad];
///iOS 15更新后,導(dǎo)航欄變白茸歧,靜止情況看不清
if (@available(iOS 13.0, *)) {
UINavigationBarAppearance *appearance = [UINavigationBarAppearance new];
[appearance configureWithOpaqueBackground];
appearance.backgroundColor = [UIColor purpleColor];
self.navigationController.navigationBar.standardAppearance = appearance;
self.navigationController.navigationBar.scrollEdgeAppearance = self.navigationController.navigationBar.standardAppearance;
} else {
// Fallback on earlier versions
}
self.navigationController.navigationBar.translucent = YES;
self.navigationController.navigationBar.subviews[0].alpha = 0;
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 設(shè)置導(dǎo)航欄為透明倦炒,并根據(jù)當(dāng)前tableView的偏移量設(shè)置對應(yīng)的 alpha
self.navigationController.navigationBar.translucent = YES;
[self setNavigationBarColorWithOffsetY:self.table.contentOffset.y];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 設(shè)置導(dǎo)航欄 為不透明
self.navigationController.navigationBar.translucent = NO;
self.navigationController.navigationBar.subviews[0].alpha = 1.0;
}
//監(jiān)聽scrollView滑動
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == self.table) {
CGFloat offsetY = scrollView.contentOffset.y;
[self setNavigationBarColorWithOffsetY:offsetY];
}
}
// 界面滑動時導(dǎo)航欄隨偏移量 實時變化
- (void)setNavigationBarColorWithOffsetY:(CGFloat)offsetY {
UIImageView *backView = self.navigationController.navigationBar.subviews[0];
if (offsetY <= 0) {
backView.alpha = 0;
self.lab.textColor = [UIColor redColor]; //這里可以根據(jù)UI設(shè)置導(dǎo)航欄上的控件顯示的顏色
} else if (offsetY > 0 && offsetY < 91) {
backView.alpha = offsetY / 91;
} else if (offsetY >= 91 ) {//&& offsetY <= NavBar_HEIGHT + 30
backView.alpha = 1;
self.lab.textColor = [UIColor yellowColor]; //這里可以根據(jù)UI設(shè)置導(dǎo)航欄上的控件顯示的顏色
}
}
這是一種實現(xiàn)方法,另一種可以使用kvo監(jiān)聽 contentOffset.y 也可以實現(xiàn)软瞎。
需要寫上
superScrollView .addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
然后逢唤,再監(jiān)聽回調(diào)中,實現(xiàn)導(dǎo)航漸變