Search code examples
swiftnavigationcontroller

Swift How can I add Navigation Controller after creating Views


I created View Controllers and I want to add Navigation Controller now. I tried embed-in Navigation Controller to My DetailViewContoller(colorful View Controller) but I got an error. main.storyboard, error. How can I add Navigation Controller ?


Solution

  • In order to set view controller as navigation controller, you can set it programmatically by calling this function in appdelegate or scenedelegate or any point.

    func setNavigationController() {
        var viewController: UIViewController
        let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "myVCID")
        let rootViewController = UINavigationController(rootViewController: viewController)
        rootViewController.setNavigationBarHidden(true, animated: false)
        self.view.window?.rootViewController = rootViewController
    }
    

    If you want to set navigation controller through storyboard, then you have to first add navigation controller and set is root view controller to the controller you want to make it navigation controller.