最近在做项目是遇到需要隐藏导航栏的需求,第一想法是在界面要显示的时候隐藏掉NaivgaionBar 然后在界面小时的时候显示出来:
-(void)viewWillAppear:(BOOL)animated {
[superviewWillAppear:animated];
// [self.navigationController setNavigationBarHidden:YES animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// [self.navigationController setNavigationBarHidden:NO animated:YES];
}
这种情况一般情况下是好用的,但是!!
但是遇到界面A隐藏导航栏 push到界面B也隐藏导航栏,这样的情况就会出现问题,尤其是使用滑动返回手势,导航栏错乱的问题很严重。后来经过分析和查阅资料得出如下方法:
所有的controller都继承自BaseViewController,那就在base里面设置
为了使滑动手势起作用需要设置下代理:
@interface BaseViewController ()<UINavigationControllerDelegate>
@end
在viewWillAppear里面设置
#pragma mark ViewWillAppear
- (void) viewWillAppear:(BOOL)animated {
[superviewWillAppear: animated];
// 1\. 返回手势代理
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
// 2\. 导航控制器代理
self.navigationController.delegate = self;
}
代理方法中如下设置:
#pragma mark - Private Methods
#pragma mark -
#pragma mark Whether need Navigation Bar Hidden
- (BOOL)needHiddenBarInViewController:(UIViewController*)viewController {
BOOLneedHideNaivgaionBar =NO;
// 需要隐藏导航栏的页面
if([viewControllerisKindOfClass: [HomeViewControllerclass]] ||
[viewControllerisKindOfClass: [SettingViewControllerclass]]||
[viewControllerisKindOfClass: [LoginViewControllerclass]]) {
needHideNaivgaionBar =YES;
}
returnneedHideNaivgaionBar;
}
#pragma mark - UINaivgationController Delegate
#pragma mark -
#pragma mark Will Show ViewController
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated {
[self.navigationController setNavigationBarHidden: [self needHiddenBarInViewController: viewController]
animated: animated];
}
至此解决问题
参考文章原文地址:导航栏隐藏 && 导航栏错乱 - CSDN博客