项目开发navigationController的使用避免不了,随着界面的丰富我们会发现navigationBar的显示/隐藏变得极其恶心.
总有那么一种情况的跳转显得十分不友好,网上找了很多资料,总于整理了一个相对简单的方式,让navigationBar完美的显示/隐藏
解决办法
给UIViewController 建一个分类 直接放代码
UIViewController+Hidden.h
#import <UIKit/UIKit.h>
@interface UIViewController (Hidden)<UINavigationControllerDelegate>
@end
UIViewController+Hidden.m
#import "UIViewController+Hidden.h"
@implementation UIViewController (Hidden)
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated {
if(viewController == self){
[navigationController setNavigationBarHidden:YES animated:YES];
}else{
//系统相册继承自 UINavigationController 这个不能隐藏 所有就直接return
if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
return;
}
//不在本页时,显示真正的navbar
[navigationController setNavigationBarHidden:NO animated:YES];
//当不显示本页时,要么就push到下一页,要么就被pop了,那么就将delegate设置为nil,防止出现BAD ACCESS
//之前将这段代码放在viewDidDisappear和dealloc中,这两种情况可能已经被pop了,self.navigationController为nil,这里采用手动持有navigationController的引用来解决
if(navigationController.delegate == self){
//如果delegate是自己才设置为nil,因为viewWillAppear调用的比此方法较早,其他controller如果设置了delegate就可能会被误伤
navigationController.delegate = nil;
}
}
}
@end
使用:
在需要隐藏navigationBar的UIViewController里这样写:(不需要隐藏的就不用管)
//注意是 viewWillAppear 方法
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//设置代理即可
self.navigationController.delegate = self;
}
//问题 navBar.delegate 和 Transition冲突
//添加是否隐藏导航
@property (assign, nonatomic) BOOL aliyun_hideNavBar;//是否隐藏导航
#pragma mark - 是否隐藏导航 setter getter
///Category添加Bool属性
- (BOOL)aliyun_hideNavBar{
return [objc_getAssociatedObject(self, @selector(aliyun_hideNavBar)) boolValue];
}
- (void)setAliyun_hideNavBar:(BOOL)aliyun_hideNavBar {
objc_setAssociatedObject(self, @selector(aliyun_hideNavBar), @(aliyun_hideNavBar), OBJC_ASSOCIATION_ASSIGN);
}
#pragma mark - 完美解决navigationBar隐藏/显示
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated {
if(viewController == self && self.aliyun_hideNavBar){
[navigationController setNavigationBarHidden:YES animated:YES];
}else{
//系统相册继承自 UINavigationController 这个不能隐藏 所有就直接return
if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
return;
}
//不在本页时,显示真正的navbar
[navigationController setNavigationBarHidden:NO animated:YES];
//当不显示本页时,要么就push到下一页,要么就被pop了,那么就将delegate设置为nil,防止出现BAD ACCESS
//之前将这段代码放在viewDidDisappear和dealloc中,这两种情况可能已经被pop了,self.navigationController为nil,这里采用手动持有navigationController的引用来解决
if(navigationController.delegate == self){
//如果delegate是自己才设置为nil,因为viewWillAppear调用的比此方法较早,其他controller如果设置了delegate就可能会被误伤
navigationController.delegate = nil;
}
}
}