1

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

Community
  • 1
  • 1
Pangu
  • 3,721
  • 11
  • 53
  • 120

1 Answers1

0

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

Mark
  • 7,167
  • 4
  • 44
  • 68
  • how does this help me perform 2 different types of segue while maintaining the navigation bar? – Pangu Apr 01 '17 at 03:40
  • You're not maintaining the original navigation bar. When you present VC2 modally, you're essentially creating another navigation stack (and without embedding it in a navigation controller, the stack will always have 1 view controller and no bar). The second navigation controller I added should instead be presented modally, thus giving you the navigation bar for VC2. – Mark Apr 01 '17 at 03:43
  • 1
    is there no way to do it programmatically without using storyboard to embed another navigation controller? – Pangu Apr 01 '17 at 03:48
  • Not in the way you were trying. You can't change the destination view controller during a segue, and you have your segue hooked up directly to VC2. – Mark Apr 01 '17 at 03:50