I\'m making a game using SpriteKit. I have 3 viewControllers: selecting level vc, game vc, and win vc. After the game is over, I want to show the win vc, then if I press OK
Swift 5 (and possibly 4, 3 etc)
presentingViewController?.presentingViewController?
is not very elegant and doesn't work in some instances. Instead, use segues
.
Let's say that we have ViewControllerA
, ViewControllerB
, and ViewControllerC
. We are at ViewControllerC
(we landed here through ViewControllerA
-> ViewControllerB
, so if we do dismiss
we will go back to ViewControllerB
). We want from ViewControllerC
to jump straight back to ViewControllerA
.
In ViewControllerA
add the following action in your ViewController class:
@IBAction func unwindToViewControllerA(segue: UIStoryboardSegue) {}
Yes, this line goes in the ViewController of the ViewController you want to go back to!
Now, you need to create an exit segue from the ViewControllerC
's storyboard (StoryboardC
). Go ahead and open StoryboardC
and select the storyboard. Hold CTRL down and drag to exit as follows:
You will be given a list of segues to choose from including the one we just created:
You should now have a segue, click on it:
Go in the inspector and set a unique id:
In the ViewControllerC
at the point where you want to dismiss and return back to ViewControllerA
, do the following (with the id we set in the inspector previously):
self.performSegue(withIdentifier: "yourIdHere", sender: self)
Adding on to Phlippie Bosman's answer, when calling
self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
if you don't want to see (what would be the presentingViewController
) you can do something like
self.presentingViewController?.view.addSubview(self.view)
This seems a bit hacky, but so far it's been the only way I've been able to make it seem like two view controllers are dismissing in unison.
There's special unwind segue intended to roll back view stack to certain view controller. Please see my answer here: how to dismiss 2 view controller in swift ios?