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
You can dismiss WinVC's presenting controller (GameViewController) in the completion block:
let presentingViewController = self.presentingViewController
self.dismissViewControllerAnimated(false, completion: {
presentingViewController?.dismissViewControllerAnimated(true, completion: {})
})
Alternatively, you could reach out to the root view controller and call dismissViewControllerAnimated, which will dismiss both modal viewcontrollers in a single animation:
self.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: {})
You should be able to call:
self.presentingViewController.dismissViewControllerAnimated(true, completion: {});
(You may need to add ?
or !
somewhere - I'm not a swift developer)
I had some animation issues when trying the accepted answer in my application. The previously presented views would flash or try to animate on the screen. This was my solution:
if let first = presentingViewController,
let second = first.presentingViewController,
let third = second.presentingViewController {
second.view.isHidden = true
first.view.isHidden = true
third.dismiss(animated: true)
}
Although Rafeels answer is acceptable. Not everybody uses Segue's.
For me the following solution works best
if let viewControllers = self.navigationController?.viewControllers {
let viewControllerArray = viewControllers.filter {
$0 is CustomAViewController || $0 is CustomBViewController }
DispatchQueue.main.async {
self.navigationController?.setViewControllers(viewControllerArray,
animated: true)
}
}
Swift 4.0
let presentingViewController = self.presentingViewController
presentingViewController?.presentingViewController?.presentingViewController?.dismiss(animated: false, completion: nil)
@Ken Toh's comment was what worked for me in this situation -- call dismiss from the view controller that you want to show after everything else is dismissed.
If you have a "stack" of 3 presented view controllers A
, B
and C
, where C
is on top, then calling A.dismiss(animated: true, completion: nil)
will dismiss B and C simultaneously.
If you don't have a reference to the root of the stack, you could chain a couple of accesses to presentingViewController
to get to it. Something like this:
self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)