Search code examples
iosswiftuikit

NavigationBar can't display title


I create a UINavigationController object, but it can't set the title.

class LogInSwitchingViewController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.white

        self.navigationItem.title = "This is title"
        self.navigationBar.tintColor = UIColor.black

        let vc1 = UIViewController()
        vc1.view.backgroundColor = UIColor.brown
        self.pushViewController(vc1, animated: true)
    }

Solution

  • You need to update the title property of the visible view controller, not the navigation controller itself:

    let vc1 = UIViewController()
    vc1.title = "This is title"
    vc1.view.backgroundColor = UIColor.brown
    self.pushViewController(vc1, animated: true)