以编程方式创建 ViewController 时,如何将其视图设置为 SKVIew 类型? [英] When programatically creating a ViewController, how can I set its view to be of type SKVIew?
问题描述
我正在 XCode 上开发 iOS 游戏.我有几个 SKScene,每个都与一个 UIViewController 类相关联.所以在每个视图控制器的 viewDidLoad 中,我创建了
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]
我想避开故事板.但是,当我将 ViewController 从第一个视图控制器呈现到下一个时,应用程序在[skView present scene]"行崩溃,因为它认为新视图控制器的视图仍然是 UIView ('-[UIView presentScene:]: unrecognized selector sent实例).
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).
我该如何解决这个问题?具体来说,在创建第二个视图控制器(以编程方式)时,如何将其视图更改为 SKview 而不是 UIview 类型?(我应该注意我希望场景与视图控制器是 1:1 的,因为几乎所有场景都是弹出窗口,比如在游戏中弹出的暂停菜单或弹出设置等)
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)
推荐答案
尝试在自定义 ViewController 上实现 loadView 方法,如下所示:
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))
}
这是 Apple 的文档所述:
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.
这篇关于以编程方式创建 ViewController 时,如何将其视图设置为 SKVIew 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!