Josh Kahane
Josh Kahane

Reputation: 17169

Add UINavigationController on top of Main UIViewController?

I have a standard UIViewController which works a charm. However, I want to add a UINavigationController on top of this as a subview, add and remove it at will. However, it seems you can't simply add another controller onto a current controller as a subview. So how do I go about this?

Thanks.

Upvotes: 1

Views: 485

Answers (2)

bryanmac
bryanmac

Reputation: 39306

Here's some code that creates a new view in a navigation controller and shows it "on top" (presents it modally).

There's a few key things here:

If you present a nav controller modally, you need to set it's left & right buttons (if you need to) before you initWithRootController and presentModally

Even if you're current view is in a navController, if you present it modally, it needs to be wrapped in a UINavigationcontroller (there's some SO posts covering that)

UINavigationController with presentModalViewController

MyView *myView = [[MyView alloc] initWithNibName:@"MyView" bundle:nil];

UIBarButtonItem *cancelBtn = [[UIBarButtonImageItem alloc] init...  

UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] init...

[[myView navigationItem] setLeftBarButtonItem:cancelBtn];
[[myView navigationItem] setRightBarButtonItem:doneBtn];  
[cancelBtn release];    
[doneBtn release];

// Edit purchase in full modal view.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myView];

[[self navigationController] presentModalViewController:navController animated:YES];

Then, from within the view you just presented modally, you can dismiss it. For example, in this code the save and cancel buttons added above are associated with these IBAction methods on the view controller you presentedModally:

- (IBAction)cancel:(id)sender
{
    NSLog(@"cancel");
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)save:(id)save
{
    NSLog(@"done");
    // do work here
    [self dismissModalViewControllerAnimated:YES];
}

Upvotes: 1

Matthew Gillingham
Matthew Gillingham

Reputation: 3429

You can add another's controllers view as subview of that viewcontroller's view

[mainViewController addSubview:anotherViewController.view];

In the case of a UINavigationController though, although I don't know what you are doing, that is not ordinarily something that you would want to do.

Have you looked at -(void)presentModalViewController:animated?

Upvotes: 0

Related Questions