Embed a UIViewController in a NavigationController using segues

23,835

In your Storyboard, you can embed a ViewController in a Navigation Controller by selecting the View Controller and then picking from the menu at the top Editor->Embed In->Navigation Controller. From another view controller, you control drag to this Navigation controller to set up the modal segue. You can also control drag to the original View Controller to set up segues to it without the Navigation Controller.

Storyboard showing a view controller both embedded in a navigation controller and not

Share:
23,835
hatunike
Author by

hatunike

Updated on July 25, 2022

Comments

  • hatunike
    hatunike almost 2 years

    I have a viewController that is usually (most often) accessed by using a push segue. This viewController needs to be embedded in a UINavigationController. So typically, this is no problem. The push segue manages pushing the viewController, and therefore the viewController has it's UINavigationController.

    My issue is that in a few cases, I'd like to present this same exact viewController using a modal segue. When I do this, the viewController is not embedded in a navigationController. Is there a way to do this using segues?

    I know this can be done purely in code without segues by creating a UINavigationController, setting the rootView as the viewController and then presenting that modally. That can be done using code like this :

    MyViewController *viewController = [[MyViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
    [self presentModalViewController:navController animated:YES];
    

    But how do I do this same thing but using Segues?

    Update


    For further clarity, here is some code to supplement how I used the accepted answer in the prepareForSegue method.

    When Using Modal Segue

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([[segue destinationViewController] isEqualToString:@"Modal to MyVC"])
        {
            UINavigationController *nav = [segue destinationViewController];
            MyViewController *vc = [nav topViewController];
            //setup vc
        }
    }
    

    When Using Push Segue

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([[segue destinationViewController] isEqualToString:@"Push to MyVC"])
        {
            MyViewController *vc = [segue destinationViewController];
            //setup vc
        }
    }