2

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.

Paresh Masani
  • 7,474
  • 12
  • 73
  • 139

2 Answers2

4

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];
}
Quxflux
  • 3,133
  • 2
  • 26
  • 46
  • You are right! That's great! It worked but I am wondering how come dismissing rootviewcontroller worked when it's not on the top? – Paresh Masani Mar 28 '12 at 18:18
  • That's because as soon as you dismiss the viewcontroller which is being presented by the root viewcontroller it will automatically dismiss all modal view controllers that this one is presenting and so on. Basically this is just a recursive call I guess. – Quxflux Mar 28 '12 at 18:23
  • Interesting but I don't feel like any controllers getting dismissed! It's directly I am getting to rootviewcontroller! – Paresh Masani Mar 28 '12 at 18:27
0

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)
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88
Himanshu Parashar
  • 478
  • 1
  • 6
  • 18