话不多说直接上代码
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// 隐藏导航栏
// [self.navigationController.navigationBar setHidden:YES];
[self.navigationController setNavigationBarHidden:YES animated:animated];
}
-(void) viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
//显示导航栏
// [self.navigationController.navigationBar setHidden:NO];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//scrollView已经有拖拽手势,直接拿到scrollView的拖拽手势
UIPanGestureRecognizer *pan = scrollView.panGestureRecognizer;
//获取到拖拽的速度 <0 向下拖动 >0 向上拖动
CGFloat velocity = [pan velocityInView:scrollView].y;
if (scrollView.contentOffset.y < 0) {
//向上拖动,隐藏导航栏
[self.navigationController setNavigationBarHidden:YES animated:YES];
}else if (scrollView.contentOffset.y > 0){
[self.navigationController setNavigationBarHidden:NO animated:YES];
//透明度
//找最大值/
// CGFloat alpha = fabs(scrollView.contentOffset.y * 1 / 136.0); // (200 - 64) / 136.0f
//计算透明度
CGFloat alpha = scrollView.contentOffset.y /64 >1.0f ? 1:scrollView.contentOffset.y/64;
if (alpha >= 1) {
// 透明度最大值
alpha = 0.99;
}
self.alphaImage = [UIImage imageWithColor:[GLOBAL_BLUE colorWithAlphaComponent:alpha]];
// [self.navigationController setDefaultNavigationBar];
//修改导航条背景图片
[self.navigationController.navigationBar setBackgroundImage:self.alphaImage forBarMetrics:UIBarMetricsDefault];
}else if(velocity == 0){
//停止拖拽
}
}
这些还不够(透明度没有),由于该控制器继承了父控制器,所以得在父控制器中判断来开启透明度
UIViewController *vc = self;
BOOL isTrue = [vc isMemberOfClass:[PositionDetailViewController class]] || [vc isMemberOfClass:[ActivityDetailViewController class]];
if (isTrue) {
//导航栏自带的毛玻璃效果
self.navigationController.navigationBar.translucent = YES;
}else{
self.navigationController.navigationBar.translucent = NO;
}
问题又来了,pop或者push回去的控制器的导航栏会跟着变化,解决方案请看如下代码:
在上级控制器中加上以下代码:
//防止进入子页面再pop回来变成透明
-(void) viewWillAppear:(BOOL)animated{
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"daohanglan"] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.translucent = NO;
}