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.
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)
}
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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With