There is a controller A ( TableViewController ), by clicking on a cell, we go to controller B ( ViewController ), it all lies in the Navigation Controller . In controller B, we can follow the link, then this code will be called, and we will modally add a new controller B, so we can add many modal views:

 UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; DetailViewController *relatedNews = [storyboard instantiateViewControllerWithIdentifier:DetailViewControllerID]; relatedNews.modalTransitionStyle = UIModalTransitionStyleCoverVertical; relatedNews.modalPresentationStyle = UIModalPresentationCurrentContext; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:relatedNews]; UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(backPressed)]; relatedNews.navigationItem.leftBarButtonItem = backButton; [[self.navigationController topViewController] presentViewController:navController animated:YES completion:nil]; -(void) backPressed { [self dismissViewControllerAnimated:NO completion:nil]; } 

When you click on the button, dismissViewControllerAnimated will be called, which will close our modal window. How to make it so that by pressing this button we close all our modal windows and return to the very first controller B, which was called push segway. So generally you can do?

    2 answers 2

    Try this:

     UIViewController *vc = self.presentingViewController; while (vc.presentingViewController) { vc = vc.presentingViewController; } [vc dismissViewControllerAnimated:YES completion:NULL]; 

    With the help of the loop, you will get to the very first controller, and calling dismissViewControllerAnimated on it will reset the entire stack. I do not guarantee that it will work, but it should

    • Thanks, corrected a little, that would work out when 1 modal window - Dmitrii
    • @ Dmitriy feel free to mark the answer as accepted :) - Sega-Zero

    That's how I corrected it a bit, which would work out when only 1 time a modal window was called:

     UIViewController *vc = self.presentingViewController; while (vc.presentingViewController) { vc = vc.presentingViewController; } if(!vc) { [self dismissViewControllerAnimated:YES completion:NULL]; } else { [vc dismissViewControllerAnimated:YES completion:NULL]; }