user1391152 user1391152 - 1 year ago 124
Swift Question

Dismiss View controller underneath current visible view controller in stack

How would I go about dismissing a view controller once a segue has been performed? Once the new view controller has animated on top, I want to dismiss the view controller underneath (the one which the segue was initially triggered from).

I tried the following code but I am getting issues with views not being in the heirarchy.

@IBAction func gotoSection1(_ sender: AnyObject) {
let presentingViewController: UIViewController! = self.presentingViewController

self.dismiss(animated: false) {
presentingViewController.dismiss(animated: false, completion: nil)

Any help would be greatly apprceiated.

Answer Source

Try this:

Add the below code to first view controller.

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
        self.dismiss(animated: true, completion: nil)

It will dismiss the first view controller before presenting second view controller on top of it.


Follow these steps and check:

  1. Create a button in 1st View controller
  2. Connect button to 2nd View controller with modal segue
  3. Implement prepareForSegue in 1st view controller
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download