在 Swift 3 / iOS 10 中,在最简单的情况下,您的导航控制器将只包含一个视图控制器,您可以使用下面的代码来显示您的视图控制器,其中包含一个包含条形按钮项的工具栏:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Show navigation controller’s built-in toolbar
navigationController?.setToolbarHidden(false, animated: false)
// Set the view controller toolbar items
let items = [UIBarButtonItem(title: "Button Text", style: .plain, target: nil, action: nil)]
setToolbarItems(items, animated: false)
}
}
但是,如果您计划在导航控制器的堆栈中包含多个视图控制器,则必须调用'UINavigationController
方法setToolbarHidden(_:animated:)
才能正确显示或隐藏导航控制器的内置工具栏:viewWillAppear()
viewWillDisappear()
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set the view controller toolbar items
let items = [UIBarButtonItem(title: "Button Text", style: .plain, target: nil, action: nil)]
setToolbarItems(items, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Show navigation controller’s built-in toolbar
navigationController?.setToolbarHidden(false, animated: false)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Hide navigation controller’s built-in toolbar
navigationController?.setToolbarHidden(true, animated: false)
}
}