I am getting this error when I call my method dismissView. Here is the method stub:
-(IBAction)dismissView
{
RootViewController *rootController = [[RootViewC
self.navigationController?.present(viewControllers, animated: true, completion: nil)
The -popToViewController
is used to pop view controllers OFF the stack, down to one that already exists. Your UINavigationController
has a stack of ViewControllers (stored in the viewControllers
property), when you popToViewController
, you're going to want to pass one of the elements in that array as the first argument.
What you most likely want to do in this case is use -popViewControllerAnimated:
, which will remove the top ViewController
from the stack
I resolved this by using pushViewController
rather than popToViewController
Swift 4
For anyone still looking for a better solution that doesn't involve the UINavigationController stack indexes, which is getting more problematic with bigger navigation stack - here's the easiest way to solve this:
if let destinationViewController = navigationController?.viewControllers
.filter(
{$0 is DestinationViewController})
.first {
navigationController?.popToViewController(destinationViewController, animated: true)
}
The UINavigationController
has a stack of ViewControllers
which is stored in the viewControllers(NSArray) property. Enumerate to the required ViewController
and pop to that ViewController
.
Following code should solve the problem.
-(IBAction)dismissView
{
NSArray *array = self.navigationController.viewControllers;
for (id controller in array) {
if ([controller isKindOfClass:[RootViewController class]]) {
[self.navigationController popToViewController:controller animated:YES];
}
}
}