iOS導航欄標題錯亂的解決方法

weixin_33860722發表於2017-04-23

一般隱藏和顯示導航欄,只要在基類如下寫就好:

-(BOOL)needHiddenNavigationBar:(UIViewController *)vc{
    
    BOOL isHidden = NO;
    if ([NSStringFromClass([vc class]) isEqualToString:@"ViewController"]||
        [NSStringFromClass([vc class]) isEqualToString:@"ViewController_1"]) {
        
        isHidden = YES;
    }
    return isHidden;
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:[self needHiddenNavigationBar:self] animated:animated];
}

但當在一種特殊情況下,就是在第一第二個控制器隱藏導航欄時,當在第二控制器右滑一點點在回來時在第四個控制器會還是會出現導航欄混亂的情況。

3290400-25ebebc3da78ef93.gif
-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    NSLog(@"\n%@==%@",NSStringFromClass([self class]),self.navigationController.navigationBar.items);
    NSLog(@"\n%@==%@",NSStringFromClass([self class]),self.navigationController.viewControllers);

}```
結果為:

2017-04-23 14:22:15.810 導航欄[2008:53347]
ViewController_3==(
"<<UINavigationItem: 0x6000001cbb80>: title:'ViewController'>",
"<<UINavigationItem: 0x6080001cbe50>: title:'ViewController_1'>",
"<<UINavigationItem: 0x6080001cc030>: title:'ViewController_2'>"
)
2017-04-23 14:22:15.811 導航欄[2008:53347]
ViewController_3==(
"<ViewController: 0x7fc822103a80>",
"<ViewController_1: 0x7fc8206056c0>",
"<ViewController_2: 0x7fc820510040>",
"<ViewController_3: 0x7fc820615db0>"
)```
少一個item 我偶然看到支付寶也出現此現象 他的做法是在新增一個item。

-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    NSLog(@"\n%@==%@",NSStringFromClass([self class]),self.navigationController.navigationBar.items);
    NSLog(@"\n%@==%@",NSStringFromClass([self class]),self.navigationController.viewControllers);
    if (self.navigationController.navigationBar.topItem != self.navigationItem && ![self needHiddenNavigationBar:self]) {
        
        [self.navigationController setNavigationBarHidden:YES animated:animated];
        [self.navigationController setNavigationBarHidden:NO animated:animated];
    }

}

這樣就可以了,圖


3290400-b3dfa315cfc545a4.gif

demo傳送門

相關文章