iOS 14.2,当我尝试使用下面的代码片段以编程方式呈现 NavigationController Controller 时。
@objc private func handleClick() {
let viewController = MyViewController()
self.present(viewController, animated: true, completion: nil)
}
新 Controller 中的栏标题不会被渲染。我错过了什么吗?
class MyViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "TEST" // NOT WORK
self.navigationItem.title = "Title" // NOT WORK
}
}
还尝试使用下面的代码片段将常规 View Controller 嵌套到 UINavigableController 中,但标题仍然未呈现。
@objc private func handleHelpClick() {
let innerVC = MyInnerViewController()
innerVC.title = "TEST"
let viewController = UINavigationController(rootViewController: innerVC)
self.present(viewController, animated: true, completion: nil)
}
最佳答案
文档说:
A navigation controller builds the contents of the navigation bar dynamically using the navigation item objects (instances of the UINavigationItem class) associated with the view controllers on the navigation stack.
https://developer.apple.com/documentation/uikit/uinavigationcontroller
因此,根据我的理解,您必须为 UIViewController
本身设置标题,而不是为 UINavigationController
设置标题。
示例:
class MyViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
class ViewController: UIViewController {
private lazy var button: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Display NavVC", for: .normal)
btn.setTitleColor(.blue, for: .normal)
btn.addTarget(self, action: #selector(displayNavVC), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
configureButton()
}
private func configureButton() {
view.addSubview(button)
NSLayoutConstraint.activate([
button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
@objc
private func displayNavVC() {
let vc = UIViewController()
vc.title = "abc"
let navigationVC = MyViewController(rootViewController: vc)
self.present(navigationVC, animated: true, completion: nil)
}
}
结果:
关于iOS 14 导航栏标题未显示在以编程方式创建的 UINavigationController 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64411359/