Search code examples
iosswiftswift3uinavigationcontroller

How to embed a UINavigationController in prepareForSegue?


Currently I have a VC1 of type UITableViewController that is embedded in UINavigationController. When the user selects a cell, it performs a push segue to VC2 also of type UITableViewController. That is fine because the navigation bar is still present.

However in VC1, there is a UIBarButtonItem in the navigation bar, that upon tapped, also segues to VC2 and performs different things, but it uses all the same menu layout.

Using the UIBarButtonItem to segue to VC2, I like to perform a modal segue to distinguish between the two actions.

I know that modal segues encompasses the whole screen, and any top bars will be removed.

I followed this question: Modal segue, navigation bar dissapears

One of the answers provided shows how to embed a UINavigationController in prepareForSegue, so I followed it and implemented:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "AddSegue"
    {
        let navigationController: UINavigationController = segue.destination as! UINavigationController

        var addVC: VC2 = VC2()

        addVC = navigationController.viewControllers[0] as! VC2

    }
}

However, I get the error:

Could not cast value of type 'VC2' to 'UINavigationController'

How can I properly embed a UINavigationController in prepareForSegue because I need to pass data between different view controllers.

Here's my storyboard:

enter image description here


Solution

  • The segue you're intersecting is to your VC2, not a navigation controller. You're going to need to update the "AddSegue" segue to point to a navigation controller, then link your VC2 as the root view controller of the navigation controller.

    If you post your storyboard, I can give you more details on how to do this.

    EDIT: Here's how you should set up your storyboard. It might get a bit weird, since VC2 has two parent navigation controllers, but it should be fine.

    enter image description here