阅读 438

iOS 正确隐藏导航栏的方式

大憨 2021-08-08 16.51.02.gif

简介

在项目中经常碰到首页顶部是无限轮播或透明背景图,需要靠最上面显示.有的设置导航栏为透明等一系列的方法,如何做呢 ?这里给出两种方法.

第一种做法

注意这里一定要用动画的方式隐藏导航栏,这样在使用滑动返回手势的时候效果最好,和上面动图一致.这样做有一个缺点就是在切换tabBar的时候有一个导航栏向上消失的动画.


- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated]; 
    self.navigationController.navigationBar.hidden = YES;

}
 

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated]; 
    self.navigationController.navigationBar.hidden = NO;

}
复制代码

第二种做法

设置self为导航控制器的代理,实现代理方法,在将要显示控制器中设置导航栏隐藏和显示,使用这种方式不仅完美切合滑动返回手势,同时也解决了切换tabBar的时候,导航栏动态隐藏的问题。最后要记得在控制器销毁的时候把导航栏的代理设置为nil。

@interface HomeController () <UINavigationControllerDelegate>

@end

@implementation HomeController 

- (void)viewDidLoad {
   [super viewDidLoad]; 
   // 设置导航控制器的代理为self
   self.navigationController.delegate = self;
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
   // 判断要显示的控制器是否是自己
   BOOL isShowHomePage = [viewController isKindOfClass:[self class]]; 
   [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void)dealloc {
   self.navigationController.delegate = nil;
}

复制代码

第三种做法

主要是针对A隐藏Nav, A push 到B,B也需要隐藏Nav的这种情况

1、自定义UINavigationController

#import "NavigationController.h"
#import "ViewController.h"
#import "WYTargetVC.h"


@interface NavigationController ()<UINavigationControllerDelegate, UIGestureRecognizerDelegate>

@end

@implementation NavigationController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.delegate = self;
    // 设置全屏滑动返回
    // 注意`setNavigationBarHidden:YES`设置这行代码后会导致Nav的滑动返回手势失效,
    id target = self.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
    [self.view addGestureRecognizer:pan];
    self.interactivePopGestureRecognizer.enabled = NO;
}

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


#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断如果是需要隐藏导航控制器的类,则隐藏
    BOOL isHideNav = ([viewController isKindOfClass:[ViewController class]] || 
                      [viewController isKindOfClass:[WYTargetVC class]]);
    
    [self setNavigationBarHidden:isHideNav animated:YES];
}
复制代码
文章分类
iOS
文章标签