简体   繁体   English

弹出根视图控制器时无法更新导航栏

[英]can't update navigationbar when popping to root view controller

I have a UITabBar . 我有一个UITabBar In one tab is a UINavigationController . 在一个选项卡中是UINavigationController Let's say the 2nd or 3rd UIViewController in the stack has this: 假设堆栈中的第二个或第三个UIViewController具有以下内容:

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. 如果单击当前选项卡,它将在导航控制器上popToRootViewController() The problem is, in viewWillDisappear(:) of my current tab the navigationController is nil. 问题是,在我当前选项卡的viewWillDisappear(:)中, navigationController为零。 So the navigationBar remains hidden. 因此,navigationBar保持隐藏状态。

What's the proper way to handle this? 处理此问题的正确方法是什么? Should I just set the navigation bar to visible in the root view controller's viewDidAppear ? 我是否应该将导航栏设置为在根视图控制器的viewDidAppear可见? That seems hacky. 这似乎很客气。

You should override the viewWillAppear in the rootViewController and setNavigationBarHidden from there. 您应该override rootViewControllerviewWillAppear并从那里override setNavigationBarHidden navigationController is nil at viewDidDisappear because it has already been popped off the navigation stack. navigationControllerviewDidDisappear处为nil ,因为它已从导航堆栈中弹出。

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. 如果其他人看到了,我不知道为什么当popToRootViewController()时,在viewWillDisappear之前将self.navigationController的引用设置为nil,但是我发现的解决方法只是存储您自己的引用。

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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