iPhone - dismiss multiple ViewControllers

后端 未结 22 3113
粉色の甜心
粉色の甜心 2020-11-28 04:46

I have a long View Controllers hierarchy;

in the first View Controller I use this code:

SecondViewController *svc = [[SecondViewController alloc] i         


        
22条回答
  •  情书的邮戳
    2020-11-28 05:37

    Say your first view controller is also the Root / Initial View Controller (the one you nominated in your Storyboard as the Initial View Controller). You can set it up to listen to requests to dismiss all its presented view controllers:

    in FirstViewController:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        // listen to any requests to dismiss all stacked view controllers
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissAllViewControllers:) name:@"YourDismissAllViewControllersIdentifier" object:nil];
    
        // the remainder of viewDidLoad ...
    }
    
    // this method gets called whenever a notification is posted to dismiss all view controllers
    - (void)dismissAllViewControllers:(NSNotification *)notification {
        // dismiss all view controllers in the navigation stack
        [self dismissViewControllerAnimated:YES completion:^{}];
    }
    

    And in any other view controller down the navigation stack that decides we should return to the top of the navigation stack:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"YourDismissAllViewControllersIdentifier" object:self];
    

    This should dismiss all modally presented view controllers with an animation, leaving only the root view controller. This also works if your initial view controller is a UINavigationController and the first view controller is set as its root view controller.

    Bonus tip: It's important that the notification name is identical. Probably a good idea to define this notification name somewhere in the app as a variable, as not to get miscommunication due to typing errors.

提交回复
热议问题