简体   繁体   English

在didMoveToView方法中将变量分配为rootViewController不起作用

[英]assigning variable as rootViewController in didMoveToView method doesn't work

When I create a variable in SpriteKit's default "GameScene" class: 当我在SpriteKit的默认“ GameScene”类中创建变量时:

var viewController = self.view?.window?.rootViewController as GameViewController

it works in the touchesBegan method and a few others, however, it always causes an error when declared in "didMoveToView". 它适用于touchesBegan方法和其他一些方法,但是,它在“didMoveToView”中声明时总是会导致错误。 In a game I'm creating I need it to be called in this method. 在我正在创建的游戏中,我需要在此方法中调用它。

The error that comes up is the 出现的错误是

"EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0" “EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0”

error. 错误。 There is no further information or crashlog. 没有进一步的信息或崩溃日志。

Thanks to anyone who can aid me in this time of great woe. 感谢任何能帮助我度过这段悲惨世界的人。

self.view?.window is nil when the didMoveToView is called. self.view?.windowdidMoveToView self.view?.window nil It's added to the window hierarchy only after everything is initialized. 仅在初始化所有内容后,它才会添加到window hierarchy What you can do is create a gameViewController property inside the GameScene and assign it inside GameViewController before presentScene is called. 你可以做的就是创建一个gameViewController属性里面GameScene和分配这里面GameViewController之前presentScene被调用。

class GameScene: SKScene,SKPhysicsContactDelegate {
    weak var gameViewController : GameViewController? = nil
}

Inside GameViewController GameViewController内部

override func viewDidLoad() {
    super.viewDidLoad()

    //Other code

    scene.gameViewController = self
    skView.presentScene(scene)
}

You can access it like this 您可以像这样访问

override func didMoveToView(view: SKView) {
    println(self.gameViewController?.yourPropertyName)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM