2
votes

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
How do you create the second view controller. If you aren't using storyboard/nib then it is up to you to create the SKView and assign it as the view - you can't just retrieve it - Paulw11
view controller is created and presented in the first view controller like: UIVIewController *test = [[MyViewController2 alloc] init]; [self presentViewController: test animated: YES]; - user3797886
So then in the initialiser for the view controller you are responsible for the allocation of an SKView and assigning it to the view property of the controller. - Paulw11
I've managed to conclude that, but to the best of my knowledge, my solution doesn't work (below). How would I allocate the SKview? The result below just animates over my current screen with a grey screen. UIVIewController *test = [[MyViewController2 alloc] init]; test.view = [[SKView alloc] init]; [self presentViewController: test animated: YES]; - user3797886
No, you need to modify theinit method of your custom UIViewController subclass to initialise your SKView - Paulw11

1 Answers

8
votes

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.