Search code examples
iosswiftuiviewcontrollersegueuistoryboardsegue

is there a way of dismissing two uiViewControllers at the same time in Swift?


In my swift app I have a UIViewController with a button. This button opens up the UIViewController number 2 and there user has another button. When user presses it - he opens UIViewController number 3. There is also a button and when user presses it - he calls the code:

self.dismissViewControllerAnimated(false, completion: nil)

and thanks to it the UIViewController number 3 disappears and user sees UIViewController number 2. My question is - is there a way of also dismissing the UIViewController number 2 so that user can come back smoothly from number 3 to number 1?

For now I created a function and call it through protocol:

UIViewController number 2:

protocol HandleYourFullRequest: class {
    func hideContainer()
}


class FullRequest: UIViewController, HandleYourFullRequest{

    func hideContainer(){
       self.dismissViewControllerAnimated(false, completion: nil)
    }

    @IBAction func exitbuttonaction(sender: AnyObject) {
        self.performSegueWithIdentifier("temporarySegue", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "temporarySegue"){


        if let fullRequestDetails = segue.destinationViewController as? YourFullRequest
        {

            fullRequestDetails.delegateRequest = self
        }

    }
    }



}

UIViewController number 3:

class YourFullRequest: UIViewController{

    var delegateRequest:HandleYourFullRequest?

    @IBAction func exitbuttonaction(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)

        delegateRequest?.hideContainer()
    }
}

But with that solution when user presses the button - the UIViewController number 3 disappears and UIViewController number 2 appears for a second and disappears then. Is there a way of removing number 2 without showing it to the user and point him directly to the number 1?


Solution

  • I'm still unclear as two which button is wired to which action, but from what I can tell when the dismiss button is pressed on view controller 3 it calls self.dismissViewControllerAnimated(false, completion: nil) in view controller number 2.

    Try putting this method in view controller 3.

    @IBAction func exitButtonAction(sender: AnyObject) {
        self.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil);
    }
    

    This will work assuming that both view controllers are presented and not pushed in something like a navigation controller.