★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公眾號:山青詠芝
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/ )
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/15700051.html
➤如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
簡介
在項目中經常碰到首頁頂部是無限輪播或透明背景圖,需要靠最上面顯示.有的設置導航欄為透明等一系列的方法,如何做呢 ?這里給出三種方法.
第一種做法
注意這里一定要用動畫的方式隱藏導航欄,這樣在使用滑動返回手勢的時候效果最好,和上面動圖一致.這樣做有一個缺點就是在切換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的這種情況。自定義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]; }
但是注意setNavigationBarHidden:YES設置這行代碼后會導致Nav的滑動返回手勢失效,這也就是為什么前面我們在自定義導航的時候需要設置全屏滑動返回了。
