'Tried to pop to a view controller that doesn&

2019-03-18 13:02发布

I am getting this error when I call my method dismissView. Here is the method stub:

-(IBAction)dismissView
{
    RootViewController *rootController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
    [self.navigationController popToViewController:rootController animated:YES];
}

That should work, and I've checked, rootController is initialized and allocated. Any ideas?

8条回答
萌系小妹纸
2楼-- · 2019-03-18 13:17

When using Push Segues you can easily go back to the root using this method:

[self.navigationController popToRootViewControllerAnimated:YES];

When using Modal Segues (because of the word dismiss in the question and as a general reference) you can dismiss the view controller using this method:

[self dismissViewControllerAnimated:YES completion:nil];
查看更多
放我归山
3楼-- · 2019-03-18 13:25

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];

        }
    }
}
查看更多
甜甜的少女心
4楼-- · 2019-03-18 13:28

Swift:

self.navigationController?.popToViewController ((self.navigationController?.viewControllers[1]) as! Your_ViewController, animated: true)

Objective-C:

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
查看更多
Fickle 薄情
5楼-- · 2019-03-18 13:30

You're allocating the RootViewController right there. It does not exist in the navigation controller's stack, so no matter how far you pop, you won't reach it.

查看更多
Emotional °昔
6楼-- · 2019-03-18 13:33

I had this problem recently and solved with something like this...

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
查看更多
smile是对你的礼貌
7楼-- · 2019-03-18 13:37

If you are using Storyboads, use this segue:

#import "PopToControllerSegue.h"

@implementation PopToControllerSegue

- (void) perform
{
    UIViewController *sourceViewController = (UIViewController *)self.sourceViewController;
    UIViewController *destinationViewController = (UIViewController *)self.destinationViewController;

    for (UIViewController* controller in sourceViewController.navigationController.viewControllers) {
        if ([controller isKindOfClass:destinationViewController.class]) {
            [sourceViewController.navigationController popToViewController:controller animated:YES];
            return;
        }
    }

    NSLog(@"PopToControllerSegue has failed!");
}

@end
查看更多
登录 后发表回答