iOS: popToRootViewController for presentViewControllers architecture
-
27-05-2021 - |
Question
I know that I can use popToRootViewController if I have navigationController in my project but my whole project is based on presentViewControllers and there is a scenario where I am navigating to multiple levels. If there is only one level I can get back to root view controller by dismissing current view controller but I am not able to figure out how to navigate back to root view controller when I am down to more than one level. Could someone please advice me here?
I tried to use following code but my App crashes!
- (IBAction)mainMenuButtonPressed:(id)sender {
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
[self presentModalViewController:delegate.window.rootViewController animated:YES];
}
Thanks.
Solution
If I understood you right then you are presenting several modal viewcontrollers and want to get back to the root viewcontroller. If that's right then the following code should work for you:
- (IBAction)mainMenuButtonPressed:(id)sender {
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate.window.rootViewController dismissModalViewControllerAnimated:YES];
}
OTHER TIPS
Swift Version
var = APP_DELEGATE = UIApplication.sharedApplication().delegate as! AppDelegate
APP_DELEGATE.window?.rootViewController?.dismissViewControllerAnimated(true, completion: nil)
Swift3
let APP_DELEGATE = UIApplication.shared.delegate as! AppDelegate
APP_DELEGATE.window?.rootViewController?.dismiss(animated: true, completion: nil)