iOS 导航栏 切换界面的显示与隐藏 与透明度渐变
2018-05-03 本文已影响55人
滴答大
最近公司APP新版界面新增了一个效果,轮播置顶,滑动页面使导航栏背景渐变显示。push到下一页导航栏设置同一个图片。我是在导航控制器里设置的导航栏图片,这样每个push进去的页面都是要求的效果。在需要导航栏透明的页面单独处理就好了。下面说说我遇到的坑:
一、切换界面的显示与隐藏
做法一、
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.navigationController.navigationBar.translucent = YES;
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
self.navigationController.navigationBar.translucent = NO;
NSString *imgName = @"";
if (KscreenHeight == 812.0) {
imgName = @"naviBarX";
}else{
imgName = @"naviBar.jpg";
}
[self.navigationController.navigationBar setBackgroundImage:
[UIImage imageNamed:imgName] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}
这段代码可以实现导航栏的透明,在push到下一个页面时显示导航栏背景图片。同样存在两个问题:(做了效果视频没法上传)
1、手动返回时,上一个页面会有一个闪现的导航栏图片隐藏动画
2、滑动返回时,返回过程导航栏是透明的,特别丑;
改进做法二、
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
这种做法解决了做法一出现的问题,不再有闪现消失的动画,滑动返回也实现了很好的平滑效果,但是出现了另外一个问题:
列表视图会因为animated动画效果向上移动,仍然有一点瑕疵,继续改进;
改进三、
出现二的情况是因为 animated动画效果设置成YES,但是不设置yes就会出现侧滑返回时 导航栏变为透明。因而animated动画效果设置成viewWillDisappear:(BOOL)animated的animated效果;
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:animated];
}
到此完美解决了导航栏界面的显示与隐藏出现的问题。
二、导航栏透明度渐变的思路:
setNavigationBarHidden 方法会使得导航栏的leftBarButtonItem、rightBarButtonItem失效,需要自定义导航栏的视图。
- (UIView*)naviBgView {
if (_naviBgView == nil) {
_naviBgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width, kTopHeight)];
_naviBgView.userInteractionEnabled = YES;
[self.navigationController.view insertSubview:_naviBgView belowSubview:self.navigationController.navigationBar];
}
return _naviBgView;
}
滑动实现渐变:
-(void)scrollViewDidScroll:(UIScrollView*)scrollView{
//在这里监听offset的变化
CGFloat alpha = (scrollView.contentOffset.y+kTopHeight-20)/100;
self.naviBgView.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:alpha];
}