iOS导航栏优化记录

之前导航栏隐藏一直是用的

self.navigationController.navigationBarHidden = YES;

最近突然发现项目中所有的从隐藏导航栏的界面A进入不隐藏导航栏的界面B,在从B返回A的时候导航栏会莫名其妙消失 一半,侧滑返回试了下果然有问题,一顿百度后发现大牛都是用的
[self.navigationController setNavigationBarHidden:YES animated:YES];

【iOS导航栏优化记录】然后果断换掉了,这样确实解决了这个问题,但是我这个A界面还跳到了另一个隐藏导航栏的界面C,本来用第一种方法的时候 C界面返回没有问题,但是换成第二种方法后C界面返回A界面的时候就会瞬间显示导航栏,看着相当的丑(就是一个bug)。
遇到这样的问题也很摸不着头脑,果断一通百度,然后百度到了这样一些代码:
id tc = self.transitionCoordinator; if(tc && [tc initiallyInteractive]) { [tc notifyWhenInteractionEndsUsingBlock: ^(id context) { if([context isCancelled]) { // do nothing! }else{// not cancelled, do it [self.navigationController setNavigationBarHidden:YES animated:YES]; } }]; }else{// not interactive, do it [self.navigationController setNavigationBarHidden:YES animated:YES]; }

并不懂是什么意思,然后就搜了下 UIViewControllerTransitionCoordinator,找到个这https://blog.csdn.net/yinxiaochong/article/details/47425055
看完依然很懵逼,算了,点进去看下API吧,这里就不再详细描述API了(一堆英语,没看明白就不献丑了)。
在C界面的viewwilldisappear方法中添加了下边:
id tc = self.transitionCoordinator; if(tc && [tc initiallyInteractive]) { [tc notifyWhenInteractionEndsUsingBlock: ^(id context) { @strongify(self); if([context isCancelled]) { // do nothing! [self.navigationController setNavigationBarHidden:YES animated:NO]; }else{// not cancelled, do it [tc animateAlongsideTransition:^(id_Nonnull context) { [self.navigationController setNavigationBarHidden:YES animated:NO]; } completion:^(id_Nonnull context) { [self.navigationController setNavigationBarHidden:NO animated:NO]; }]; } }]; }else{// not interactive, do it [tc animateAlongsideTransitionInView:self.view animation:^(id_Nonnull context) { @strongify(self); [self.navigationController setNavigationBarHidden:YES animated:NO]; } completion:^(id_Nonnull context) { @strongify(self); [self.navigationController setNavigationBarHidden:NO animated:NO]; }]; }

返回A界面走的是第二层if判断的else里边的代码,就是让它返回的时候先隐藏导航栏,返回完成后再显示。
至于第一次if判断的else里边的代码是C界面中还能跳转到一个没有导航栏的D界面,在跳转过程中也不能显示导航栏,所以做了隐藏操作,但是这个animateAlongsideTransitionInView:是个回调方法,我再D界面显示出来的时候才会调用里边的代码,所以在D界面的viewwillappear方法里也要做一些操作:
id tc = self.transitionCoordinator; if(tc && [tc initiallyInteractive]) { [tc notifyWhenInteractionEndsUsingBlock: ^(id context) { @strongify(self); if([context isCancelled]) { // do nothing! }else{// not cancelled, do it [tc animateAlongsideTransition:^(id_Nonnull context) { @strongify(self); [self.navigationController setNavigationBarHidden:YES animated:NO]; } completion:^(id_Nonnull context) { @strongify(self); [self.navigationController setNavigationBarHidden:YES animated:NO]; }]; } }]; }else{// not interactive, do it [tc animateAlongsideTransition:^(id_Nonnull context) { @strongify(self); [self.navigationController setNavigationBarHidden:YES animated:NO]; } completion:^(id_Nonnull context) { @strongify(self); [self.navigationController setNavigationBarHidden:YES animated:NO]; }]; }

这样做了之后这个部分的导航栏就没有问题了,当然后边还遇到了比这个还复杂的问题,但是基本上也是用的这个的解决思路给解决了。

    推荐阅读