Coder1000 Coder1000 - 4 months ago 74x
iOS Question

How can I dismiss a ViewController from my GameScene.swift?

QUESTION: How can I dismiss a ViewController from my GameScene.swift ?

SITUTATION: I have 2 VCs in my SpriteKit Game, like so:

ViewController.swift ----Press Play-----> GameViewController

When the player loses, I want to dismiss the GameViewController so the player can press play again. I check for the player's loss in my GameScene.swift and would like to dismiss the GameVC from there.

N.B.: Googled this without success.


1) Creating a gameVC instance in my GameScene.swift and dismissing it like so:

let gameVC = GameViewController()
gameVC.dismissViewController(false,completion: nil)

2) Doing:

self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil)

Those don't work for obvious reasons ^^


You don't want to "grab" the existing instance:

You need to either hand GameScene a reference to the view controller so it can dismiss it, or use the delegate pattern to communicate backwards to a controlling object that the VC should be dismissed/dismiss itself.

A simple example… you can add a GameViewController property to GameScene, then dismiss the VC at the appropriate time:

class GameScene: SKScene {
    var gameVC: GameViewController?

    func gameDidEnd() {
        gameVC?.dismissViewControllerAnimated(true) {
            // if desired, do any cleanup after the VC is dismissed

Then, just set this property when creating the GameScene object in the first place:

if let gameScene = GameScene(fileNamed: "MyScene") {
    gameScene.gameVC = someGameVC

This simple approach will tightly couple GameScene and GameViewController, making it a bit more difficult if you ever want to use one of these objects without the other. But for this simple use case, it may be fine.