Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed a UIViewController in a NavigationController using segues

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
    }
}
like image 439
hatunike Avatar asked Apr 27 '13 15:04

hatunike


People also ask

How do you add embed segue to a storyboard?

To create a segue between view controllers in the same storyboard file, Control-click an appropriate element in the first view controller and drag to the target view controller. The starting point of a segue must be a view or object with a defined action, such as a control, bar button item, or gesture recognizer.


1 Answers

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

like image 82
vacawama Avatar answered Oct 04 '22 04:10

vacawama