漸變即由透明到顯現(xiàn),由看得見到消失不見
原理: UIScrollView的偏移量,作差值公式的alpha變化設(shè)置導航欄及其子視圖的顏色和透明度的變化
1.去除導航欄及其底部一根礙眼的線
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//去掉導航欄與self.view中間的那根線
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
UINavigationBar * navigationBar = [UINavigationBar appearance];
navigationBar.backgroundColor = [UIColor clearColor];
navigationBar.barTintColor = [UIColor clearColor];
}
2. 恢復全局的導航欄設(shè)置,不可能說每個頁面都是漸變的,如果有那就當我沒說
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
UINavigationBar * navigationBar = [UINavigationBar appearance];
navigationBar.barTintColor = [UIColor orangeColor];
navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize: 15]};
}
3. 插值算法 這里的kNavBarHeight
是導航欄+狀態(tài)欄的高度,當然也可以是你自定義視圖的高度,只是一個定值,用于計算alpha(可以這么理解,往下拽的時候是透明的,往上推的時候到某一個點的時候就開始變色了,變著變著就不變了...)
CGFloat offsetY = scrollView.contentOffset.y;
UIColor *color = [UIColor blueColor];
if (offsetY > kNavBarHeight) {
if (offsetY > kNavBarHeight*2) {
offsetY = kNavBarHeight*2;
}
CGFloat alpha = (offsetY - kNavBarHeight)/kNavBarHeight;
//各種視圖透明度設(shè)置為alpha
}else{
//各種視圖設(shè)置為透明
}