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
}
}
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)
}
The documentation says:
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
So from my understanding you have to set the title for your UIViewController
itself instead for the UINavigationController
.
Example:
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)
}
}
Results in: