如何从Swift中的第一个ViewController隐藏导航栏?
我怎样才能从第一个ViewController或一个特定的ViewController在swift中隐藏导航栏?
我在viewDidLoad()
使用了下面的代码:
override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true }
也在viewWillAppear
:
override func viewWillAppear(animated: Bool) { self.navigationController?.isNavigationBarHidden = true }
这两种方法都隐藏了所有ViewController的导航控制器。
如果您知道所有其他视图都应该可见,则可以使用viewWillDisappear
将其设置为可见。
Swift 3
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide the navigation bar on the this view controller self.navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Show the navigation bar on other view controllers self.navigationController?.setNavigationBarHidden(false, animated: animated) }
您可以在viewWillDisappear
取消隐藏navigationController
override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.isNavigationBarHidden = false }
Swift 3
override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setNavigationBarHidden(false, animated: animated) }
在Swift 3中,您可以使用isNavigationBarHidden属性来显示或隐藏导航栏
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide the navigation bar for current view controller self.navigationController?.isNavigationBarHidden = true; } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Show the navigation bar on other view controllers self.navigationController?.isNavigationBarHidden = false; }
你也可以为此创build一个扩展,这样你就可以重复使用扩展,而不必在每个视图控制器中重复执行。
import UIKit extension UIViewController { func hideNavigationBar(){ // Hide the navigation bar on the this view controller self.navigationController?.setNavigationBarHidden(true, animated: true) } func showNavigationBar() { // Show the navigation bar on other view controllers self.navigationController?.setNavigationBarHidden(false, animated: true) } }
所以你可以使用下面的扩展方法
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) hideNavigationBar() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) showNavigationBar() }
你可以从窗口控制器(Swift3)
class WindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() window?.titleVisibility = .hidden } }