How to add a navigation controller to a UIViewController that's not the initial UIViewController

Alright, I hope the title of this question made sense. Basically, I have an app that has a login screen and once you log in it takes you to another view controller. The login screen is set as the initial view controller and it doesn't have a navigation controller since I wouldn't want the user going back to that screen unless they log out. So, I added a navigation controller through storyboard to my mainViewController which is the controller that gets presented after logging in. The navigation controller is not showing up though. I'm not sure if it has to do with the way I'm presenting the mainViewController but I'll show you my code and I'll let you be the judge!

StoryBoard Image

let pushedViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "mainViewController") as! mainViewController
self.present(pushedViewController, animated: true, completion: nil)

I never added any additional code to my AppDelegate class, so I'm not sure if I have to do something there?

2 answers

  • answered 2018-04-17 04:51 Vollan

    You can do it programmatically by setting rootViewController in a UINavigationController`

    let pushedViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "mainViewController") as! mainViewController
    let vc = UINavigationController.init(rootViewController: pushedViewController)
    self.present(vc, animated: true, completion: nil)
    

  • answered 2018-04-17 04:51 Ankit Jayaswal

    If you are taking navigation controller from storyboard, then present the navigation controller not mainViewController.

    For that:

    You can assign identifier to navigationController as "mainViewControllerNav" and then update your code as:

    let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "mainViewControllerNav")
    self.present(vc, animated: true, completion: nil)
    

    Now you are presenting the navigation controller and navigation controller will load its first viewcontroller in stack which is your "mainViewController".

    Rather:

    I will suggest you to change the root on logging in and logging out as:

    if let navVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "mainViewControllerNav") as? UINavigationController,
        let appDelegate = UIApplication.shared.delegate as? AppDelegate {
        appDelegate.window?.rootViewController = navVC
        appDelegate.window?.makeKeyAndVisible()
    }
    

    Hope this will help you.