Segue from GameScene to a viewController Swift 3

2020-07-27 06:25发布

问题:

I need to make a segue from a GameScene to a UIViewController. My code so far is the following:

In the GameViewController.swift I added:

if let view = self.view as! SKView? {
        if let scene = SKScene(fileNamed: "GameScene") {
            scene.scaleMode = .aspectFill

            scene.viewController = self
            view.presentScene(scene) 
        }
         ...

and in my GameScene.swift I added

class GameScene: SKScene, SKPhysicsContactDelegate {
    var viewController: UIViewController?

    ...

as well as

func returnToMainMenu(){

    self.viewController.performSegueWithIdentifier("push", sender: viewController)

}

So my problem is that when I state - scene.viewController = self - I get an error that says "value of type 'SKScene' has no member 'viewController'". What can I do to fix this?

回答1:

The problem is that the viewController property is declared in GameScene, but when the scene is created it is of type SKScene. The simple way to fix it would be to initialise the scene as a GameScene then you will have access to the members declared in GameScene.

if let scene = GameScene(fileNamed: "GameScene") {
    // Other code
    scene.viewController = self
}

Also, you should try an exit seque when returning to main menu, but that's another topic.