Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pop to root view controller from modal

Tags:

ios

swift

swift3

I am trying to pop to the root view controller using the following code:

self.navigationController!.popToRootViewController(animated: true)

This usually works, but I get an error when trying to use this code when the current view is a modal. How do I go about popping back to the root view controller in this situation?

Thanks in advance.

like image 719
user1391152 Avatar asked Oct 03 '16 11:10

user1391152


2 Answers

You can check that current controller is presented, if it is presented then dismiss it and the go to the rootViewController other wise go directly the rootViewController

if self.presentingViewController != nil {
    self.dismiss(animated: false, completion: { 
       self.navigationController!.popToRootViewController(animated: true)
    })
}
else {
    self.navigationController!.popToRootViewController(animated: true)
}
like image 147
Nirav D Avatar answered Oct 27 '22 17:10

Nirav D


Result:

Code

Let's say that your Modal View has the below ViewController associated.

Basically first to hide your View that is shown as a Modal, you use dismiss(animated: Bool) method from your ViewController instance.

And for the Views presented as Pushed, you could use from your navigationController property these methods for instance: popToRootViewController(animated: Bool), popViewController(animated:Bool)

class ModalViewController: UIViewController {
  
  @IBAction func backButtonTouched(_ sender: AnyObject) {
    let navigationController = self.presentingViewController as? UINavigationController
    
    self.dismiss(animated: true) {
      let _ = navigationController?.popToRootViewController(animated: true)
    }
  }
  
}
like image 20
Wilson Avatar answered Oct 27 '22 15:10

Wilson