When programatically creating a ViewController, how can I set its view to be of type SKVIew?

不羁岁月 提交于 2019-12-02 09:34:59

问题


I am developing a game in iOS on XCode. I have several SKScenes each associated with a UIViewController class. So in each of the view controller's viewDidLoad, I create

SKView *skView = (SKView *)self.view
SKScene * scene = [whateverSKScene sceneWithSize:skView.bounds.size]
[skView present scene]

I want to avoid the storyboard. However, when I presentViewController from the first view controller to the next, the app crashes at the line "[skView present scene]" because it thinks the new view controller's view is still UIView ('-[UIView presentScene:]: unrecognized selector sent to instance).

How can I fix this? Specifically, when creating the 2nd view controller (programatically), how can I change its view to be of type SKview not UIview? (I should note I want the scenes to be 1:1 with view controllers because almost all of them are popups like a pause-menu pop up over game play or settings pop up etc)


回答1:


Try implementing the loadView method on your custom ViewController, like so:

override func loadView() {
        self.view = SKView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
}

This is what Apple's documentation states:

This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.



来源:https://stackoverflow.com/questions/31085728/when-programatically-creating-a-viewcontroller-how-can-i-set-its-view-to-be-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!