在开发中, 我们经常会遇见这样场景, 在controllerA中要隐藏NavigationBar,在collectionB中要显示NavigationBar,这个时候我可以这样处理:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
这样使用不仅仅显得很麻烦,而且在viewController出现的时候navigationBar会出现明显的闪动,对于一个有强迫症的人来说,看着并没有那么丝滑的感觉了。。。
于是有了以下的解决办法:
@property(nonatomic,weak) UINavigationController *navController;
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.navigationController.delegate = self;
self.navController = self.navigationController;
}
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated
{
if(viewController == self){
[self.navController setNavigationBarHidden:YES animated:animated];
}else{
//不在本页时,显示真正的nav bar
[self.navController setNavigationBarHidden:NO animated:animated];
//当不显示本页时,要么就push到下一页,要么就被pop了,那么就将delegate设置为nil,防止出现BAD ACCESS
//之前将这段代码放在viewDidDisappear和dealloc中,这两种情况可能已经被pop了,self.navigationController为nil,这里采用手动持有navigationController的引用来解决
if(self.navController.delegate == self){
//如果delegate是自己才设置为nil,因为viewWillAppear调用的比此方法较早,其他controller如果设置了delegate就可能会被误伤
self.navController.delegate = nil;
}
}
}
于是就完美的解决了。