如何正确使用协议来调用GameViewController的功能?

时间:2016-12-12 19:26:29

标签: ios swift sprite-kit swift-protocols

我有一个GameScene.sks,GameScene类和Ga​​meViewController。我可以在不使用sk的情况下创建协议,但我想使用SKScene(fileNamed: "GameScene")来完成此任务。

当我在GameViewController中使用scene.gameDelegate = self时,viewDidload()  我收到Value of type 'SKScene' has no member gameDelegate错误。

我如何克服这个问题?

protocol GameDelegate {

    func createAds()
}

GameScene课程:

class GameScene: SKScene {

    var gameDelegate: GameDelegate!

    ...

GameViewController viewDidLoad:

        if let view = self.view as! SKView? {

            if let scene = SKScene(fileNamed: "GameScene") {

                scene.scaleMode = .aspectFill
                scene.gameDelegate = self // Value of type 'SKScene' has no member gameDelegate

                gameState = .playing
                view.presentScene(scene)
            }

            view.ignoresSiblingOrder = true

        }

1 个答案:

答案 0 :(得分:3)

将局部变量scene初始化为GameScene的{​​{1}}子类。 这看起来像是:

SKScene

还要确保 if let view = self.view as! SKView? { // change type of optionally bound constant 'scene' if let scene = GameScene(fileNamed: "GameScene") { scene.scaleMode = .aspectFill scene.gameDelegate = self gameState = .playing view.presentScene(scene) } view.ignoresSiblingOrder = true } 类符合GameViewController协议并实现所有必需的接口方法。