Search code examples
swiftpushviewcontrollerpresentmodalviewcontrollernavigationcontrollernavigationitem

How to set title of navigation item after open another view controller using with present modally - Swift


I have two view controllers in my application. Root view controller has some components and one of them is a button. That button provides to open another view controller using with present function. Second view controller(SelectTimeViewController) that opens when the button is tapped, was opened successfully. I am trying to set navigation title and items but I can not see them.

I did not use storyboard so root view controller is setting from AppDelegate.

let viewController = ViewController()
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: viewController)
window?.makeKeyAndVisible()

When tapped the button, "openVC" function is invoked.

@IBAction func openVC(_ sender: Any) {
    self.navigationController?.present(SelectTimeViewController(), animated: true, completion: nil)
}

I am trying to set title and rightBarButtonItem in SelectTimeViewController's viewDidLoad function but I can not see both of them.

override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "close"), style: .plain, target: self, action: #selector(closeIt))
        self.navigationItem.title = "Select Time"
}

In additional to this, I can see both title and right bar button item when change the "openVC" function like as bellow.

@IBAction func openVC(_ sender: Any) {
    self.navigationController?.pushViewController(vc, animated: true)
}

Solution

  • You have to push the SelectTimeViewController instead of present

    Or if you really want to present it, you should present another UINavigationController that has the rootViewController as SelectTimeViewController()