我如何隐藏导航栏从第一个ViewController或一个特定的ViewController在swift?

我在viewDidLoad()中使用了以下代码:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.isNavigationBarHidden = true
}

以及viewWillAppear:

override func viewWillAppear(animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

这两种方法都对所有viewcontroller隐藏导航控制器。


当前回答

在IOS 8中这样做

navigationController?.hidesBarsOnTap = true

但只有当它是UINavigationController的一部分时

当你想要回它时,把它设为false

其他回答

我使用了上面的一个变体,并将应用程序的各个部分嵌入到不同的navcontroller中。这样,我就不必重置可见性。例如,在启动序列中非常有用。

    /*.  Swift 5  */     
    let controller =  self.storyboard?.instantiateViewController(withIdentifier: "sc_userNavigation") as! UserNavigationViewController
    let navigationController = UINavigationController(rootViewController: controller)
    navigationController.setNavigationBarHidden(true, animated: false)
    navigationController.modalPresentationStyle = .fullScreen
    self.present(navigationController, animated: false, completion: nil)

你也可以为此创建一个扩展,这样你就可以重用扩展,而不必在每个视图控制器中反复实现这个。

import UIKit

extension UIViewController {
    func hideNavigationBar(animated: Bool){
        // Hide the navigation bar on the this view controller
        self.navigationController?.setNavigationBarHidden(true, animated: animated)

    }

    func showNavigationBar(animated: Bool) {
        // Show the navigation bar on other view controllers
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }

}

因此,您可以使用如下所示的扩展方法

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        hideNavigationBar(animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        showNavigationBar(animated: animated)
    }

如果您知道所有其他视图都应该有可见的条,您可以使用viewWillDisappear将它再次设置为可见。

迅速:

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

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

在视图中调用set hide方法Will appear和Disappear。如果不调用,视图中的方法将消失,状态为false。它将在完整的导航层次结构中隐藏导航栏

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.setNavigationBarHidden(true, animated: true)
}

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