iOS隐藏导航栏

前言(可略)

有的页面有导航栏,有的页面又不要导航栏,同时又想手势返回动画流畅。
或许会采用以下方法:

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

这个方法有两个问题:1.方法繁琐;2.B界面手势返回时,B界面导航栏消失;

对与问题2,可以改用下面解决:
[self.navigationController setNavigationBarHidden:hiden animated:animated];
但又引入一个问题,当AB界面都隐藏导航栏时,导航栏有消失和出现的动画。如何解决就是我思考的问题了。


解决方案

step1:通过运行时添加属性shouldNavigationBarHidden,标识控制器是否需要隐藏导航栏
step2:自定义导航栏,对比shouldNavigationBarHidden与导航栏navigationBarHidden,不一致时隐藏导航栏


使用方法:

在ViewController的viewDidLoad中设置
self.shouldNavigationBarHidden即可。
注意:push前设置view.backgroundColorview相关内容会导致viewDidLoad 提前的顺序问题


代码

@interface UIViewController (NavigationBarHidden)
/// 是否隐藏导航栏。默认NO。
@property (nonatomic , assign) BOOL shouldNavigationBarHidden;

@end


@interface HideNavigationController : UINavigationController

@end

#import "UIViewController+NavigationBarHidden.h"
#import 

@implementation UIViewController (NavigationBarHidden)

- (BOOL)shouldNavigationBarHidden{
    return [objc_getAssociatedObject(self, @selector(shouldNavigationBarHidden)) boolValue];
}

- (void)setShouldNavigationBarHidden:(BOOL)shouldNavigationBarHidden{
    objc_setAssociatedObject(self, @selector(shouldNavigationBarHidden), @(shouldNavigationBarHidden), OBJC_ASSOCIATION_ASSIGN);
}

@end





@implementation HideNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    if (self.viewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [super pushViewController:viewController animated:animated];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
    if (viewController.shouldNavigationBarHidden != self.navigationBarHidden) {
        [self setNavigationBarHidden:viewController.shouldNavigationBarHidden animated:animated];
    }
}

@end


对于隐藏了导航栏的控制器,手势返回也消失了。可自定义手势,在边缘开始滑动时调用interactivePopGestureRecognizer方法。可参考 iOS导航栏隐藏透明处理 && 侧滑返回手势

附上本文Demo

你可能感兴趣的:(iOS隐藏导航栏)