How can I indicate a view which has created with UIKit from a SKScene?

前端 未结 1 913
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 17:11

I have a file of SKScene which is named \"MainScene.swift\", and created a button on it for users to jump to another page. The another page was created not by SpriteKit but

1条回答
  •  时光说笑
    2021-01-16 18:13

    This sounds like a job for the delegate pattern. Add a protocol for LevelScene;

    // LevelScene.swift
    protocol LevelScene : class {
        var gameDelegate: GameDelegate? { get set }
    }
    

    Add a protocol for GameDelegate;

    // GameDelegate.swift
    protocol GameDelegate : class {
        func gameOver()
    }
    

    In your mainScene add the protocol reference and create a property called gameDelegate;

    class MainScene: SKScene, LevelScene {
        weak var gameDelegate: GameDelegate?
    }
    

    In your GameViewController add the protocol reference and implement the required protocol function - in this case it's called gameOver and seque to your UIKit View as usual;

    class GameViewController: UIViewController, GameDelegate {
        func gameOver() {
            self.performSegue(withIdentifier: ExitGameSegueKey, sender: self)
        }
    }
    

    Set the delegate to gameViewController when presenting the scene;

    scene.gameDelegate = self
    

    Then in mainScene call the delegate function when required;

    self.gameDelegate?.gameOver()
    

    0 讨论(0)
提交回复
热议问题