以编程方式创建的UINavigationController中未显示iOS 14导航栏标题 [英] iOS 14 navigation bar title is not displayed in UINavigationController created programmatically
问题描述
iOS 14.2,当我尝试通过下面的代码片段以编程方式展示NavigationController控制器时.
iOS 14.2, when I tried to present a NavigationController controller programmatically with the code snippet below.
@objc private func handleClick() {
let viewController = MyViewController()
self.present(viewController, animated: true, completion: nil)
}
新控制器中的条形标题将不会呈现.我想念什么吗?
The bar title in the new controller won't get rendered. Am I missing anything?
class MyViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "TEST" // NOT WORK
self.navigationItem.title = "Title" // NOT WORK
}
}
还尝试了下面的代码片段,将常规的View Controller嵌套到UINavigableController中,但标题仍未呈现.
Also tried the code snippet below to nest a regular View Controller into an UINavigableController but the title is still not rendered.
@objc private func handleHelpClick() {
let innerVC = MyInnerViewController()
innerVC.title = "TEST"
let viewController = UINavigationController(rootViewController: innerVC)
self.present(viewController, animated: true, completion: nil)
}
推荐答案
文档说:
导航控制器使用与导航堆栈上的视图控制器关联的导航项对象(UINavigationItem类的实例)动态构建导航栏的内容.
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
设置标题.
So from my understanding you have to set the title for your UIViewController
itself instead for the 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)
}
}
结果:
这篇关于以编程方式创建的UINavigationController中未显示iOS 14导航栏标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!