简体   繁体   中英

can't update navigationbar when popping to root view controller

I have a UITabBar . In one tab is a UINavigationController . Let's say the 2nd or 3rd UIViewController in the stack has this:

class ChildVC: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
}

If you click the current tab it will popToRootViewController() on the navigation controller. The problem is, in viewWillDisappear(:) of my current tab the navigationController is nil. So the navigationBar remains hidden.

What's the proper way to handle this? Should I just set the navigation bar to visible in the root view controller's viewDidAppear ? That seems hacky.

You should override the viewWillAppear in the rootViewController and setNavigationBarHidden from there. navigationController is nil at viewDidDisappear because it has already been popped off the navigation stack.

If anybody else sees this, I don't know why the reference to self.navigationController gets set to nil before viewWillDisappear when you popToRootViewController() but a workaround I found was just to store your own reference to it.

class ChildVC: UIViewController {
    private weak var navCtrl: UINavigationController?

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navCtrl = navigationController
        navCtrl?.setNavigationBarHidden(true, animated: false)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navCtrl?.setNavigationBarHidden(false, animated: false)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM