参考 http://www.cocoachina.com/ios/20170331/18944.html
先看一下UINavigaionBar的层次结构
1. 获取UIBarbackgroud视图,改变其透明度。
self.barImageView = self.navigationController.navigationBar.subviews.firstObject;
2. 设置导航栏的背景图
在合适的地方设置导航栏的背景图,我是在AppDelegate中设置的
[nav.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault]; //设置背景
3.在UIScrollView的delegate方法改变改变导航栏的背景的透明度
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSLog(@"y = %f",scrollView.contentOffset.y);
CGFloat offsetY = scrollView.contentOffset.y;
if(offsetY <= 85){
CGFloat alpha = MIN(1,(offsetY)/150 );
_barImageView.alpha = alpha;
}else{
_barImageView.alpha = 1;
}
NSLog(@"alpha = %f",_barImageView.alpha);
}
4.在viewWillAppear中设置_barImageView.alpha = 0
而且设置UIScrollView(tableView)的delegate = nil
viewWillDisapper同理
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.tableView.delegate = self;
_barImageView.alpha = 0 ;
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
self.tableView.delegate = nil;//为了防止页面push时,导航栏的背景还发生改变
_barImageView.alpha = 1 ;
}
https://github.com/JnLuffy/LFY_UINavigationController.navigationBar