1
votes

I am creating an app that opens with ViewController1, then a button opens another view contoller (ViewController2) with a modally segue. Then ViewController2 has a button that opens another view controller (ViewController3) using another modally segue. Both 2 and 3 view contollers have a dismiss button that dismisses the view controller.

The problem is that whenever ViewController3 uses the dismiss button, it dismisses to ViewController 2 when I want it to dismiss to ViewController1. I've tried using the dismiss action to dismiss ViewController2 one the button is pressed, but then the segue doesn't get committed.

This may be confusing so please ask questions if you need help understanding. Thanks so much in advace!

(I am using Swift 3 and Xcode 8)

3
if my understanding is correct, When you tap dismiss button on viewcontroller3, you want to go back to viewcontroller1 not viewcontroller2. is that right ?Venkat057
@iOSFreak Yes 👍🏻iFunnyVlogger

3 Answers

0
votes

Two options off the top of my head: 1. Use NotificationCenter and Send a dismiss notification that ViewController2 is listening for 2. Set a parentViewController reference on ViewController3, and then call dismiss on the parent after dismissing itself.

0
votes

This happen because all the 3 viewcontroller are in stack,whenever u dismiss the viewcontroller in top it moves to the one below it. To navigate to viewcontroller1 use:-

 if let viewcontroller1 = navigationController?.viewControllers[0]{
    _ = navigationController?.popToViewController(viewcontroller1, animated: true)

        }
0
votes

it's simple!

        //*** in ViewController2 
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.onCloseViewController2), name: NSNotification.Name(rawValue: "closeViewController2"), object: nil)

    func onCloseViewController2() {
//this function is called from notification (sent by vc3)
    self.navigationController?.dismiss(animated: true, completion: nil);
}

@IBAction func closeView2FromButton() {
//Directly close modal
    self.onCloseViewController2();
}


        //*** in ViewController3 (tap button)
    @IBAction func closeView3FromButton() {
//dismiss vc3 and send a notification to vc2
            self.navigationController?.dismiss(animated: true, completion: { 
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "closeViewController2"), object: nil);
    });
}

Remember to later remove the observers when you do not need them in your code ;)