thisiscrazy4
thisiscrazy4

Reputation: 1965

Presenting a UINavigationController from a UIViewController doesn't have default cancel button

I am trying to present a UINavigationController modally from a UIViewController. From previous experience, I'm pretty sure that when I do this there should be a cancel button by default in the navigation bar, however with the following code the navigation bar is completely blank. Any ideas?

UIViewController *rootVC = [[UIViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:rootVC];
[self presentViewController:navController animated:YES completion:nil];

Upvotes: 1

Views: 356

Answers (2)

Xu Yin
Xu Yin

Reputation: 3940

– presentViewController:animated:completion: only going to present your view controller as a modal view controller, even you set up that as a navigation controller. the easiest solution in your case is in the navController set the left bar button as the cancel button, and call dismiss when click that button,

UIBarButtonItem *cancelButton= [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(dismissViewController)];
 navController.navigationItem.leftBarButtonItem = cancelButton;

- (void)dismissViewController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

Hope that would help.

Upvotes: 0

Léo Natan
Léo Natan

Reputation: 57060

You will not get any bar button items by default. You need to either add the button before presenting, or, more correctly, add the button from inside the root view controller. Normally, you want to have delegation set up, where the presented view controller notifies the presenting view controller that it should dismiss it. Self-dismissing from inside the root view controller is usually not recommended.

Upvotes: 1

Related Questions