How can I modally present a UIViewController on another Storyboard that's embedded in a UINavigationController?

569 views Asked by At

...and have it embedded in a navigation controller.

I have a storyboard, let's call it MainStoryboard.

On main storyboard (neither is the initialViewController BTW), I have a ViewController, let's call it ViewControllerZ, embedded in a NavigationController, let's call it NavigationControllerZ.

Upon a user clicking a button... I had...

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewControllerZ *vcZ = (ViewControllerZ *)[storyboard instantiateViewControllerWithIdentifier:@"ViewControllerZ"];
vcZ.delegate = self;
vcZ.blah = blah;
[self.navigationController presentViewController:vcZ animated:YES completion:nil];

However this doesn't present me with a needed NavigationController. I need the NavigationController from MainStorybard, as the NavBar on ViewControllerZ has a UIBarButtonItem Cancel, to dismiss the modally presented view.

So to get the NavigationController I tried...

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
NavigationViewControllerA *navVcZ = (NavigationViewControllerZ *)[storyboard instantiateViewControllerWithIdentifier:@"NavigationViewControllerZ"];
ViewControllerZ *vcZ  = (ViewControllerZ *)navVcZ.topViewController;
vcZ.delegate = self;
vcZ.blah = blah;
[self.navigationController presentViewController:vcZ animated:YES completion:nil];

However, this does not work and throws a "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller ".

How can I solve this issue?

1

There are 1 answers

0
Bannings On BEST ANSWER

From the error it seems you add the navVcZ as a child view controller like this:

[self.navigationController presentViewController:vcZ animated:YES completion:nil];
[self.navigationController addChildViewController:navVcZ];

You can directly present the navVcZ:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
NavigationViewControllerA *navVcZ = (NavigationViewControllerZ *)[storyboard instantiateViewControllerWithIdentifier:@"NavigationViewControllerZ"];
ViewControllerZ *vcZ  = (ViewControllerZ *)navVcZ.topViewController;
vcZ.delegate = self;
vcZ.blah = blah;
[self.navigationController presentViewController:navVcZ animated:YES completion:nil];