Pop to root view controller from modal

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)
    }
  }
  
}

If you don't want the animations to happen, i.e. you want user to see the root view controller after the modal view is dismissed:

CATransaction.begin()
CATransaction.setCompletionBlock {
    self.dismiss(animated: true, completion: nil)
}
self.navigationController?.popViewController(animated: false)
CATransaction.commit()

Reference from: Completion block for popViewController

The above will work for popping a single view controller. If you need to pop multiple, popToRootViewController will not work (there is an unbalanced call due to animations).

In that case, use the following (manual) method to remove them:

guard let navigationController = self.navigationController else { return }
var navigationViewControllers = navigationController.viewControllers
navigationViewControllers.removeLast(navigationViewControllers.count - 1)
self.navigationController?.viewControllers = navigationViewControllers

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)
}

You have presented a ViewController, so you need to dismiss it.

To dismiss a ViewController in swift, use this:

self.dismiss(animated: true, completion: nil)

Tags:

Ios

Swift

Swift3