Search code examples
iosswiftuiviewcontrollersprite-kitskscene

Adding an SKScene to a UIViewController?


I just created a new UIViewController in interface builder. It is segued to from a UITableViewController (cell). I now want to work with an SKScene inside this UIViewController. How is this accomplished?

And for a side-note...

If the SKScene takes up the entire UIViewController.view can you overlay UIKit objects on top of the scene?

Or is it better to create a separate UIView inside the UIViewController.view to hold the SKScene, then layout the UIKit objects around this separate UIView, and let the default UIViewController.view act as a container for all these elements? If this approach is taken, theoretically speaking can these UIKit objects be accessed by the SKScene?


Solution

    1. Add an SKView to your viewController.
    2. Add an SKScene to your SKView.

    You can overlay UIKit items from inside your SKScene. This is how I use collection and table views in my games. However they would need to be added as a subview on the SKView holding your SKScene.

    SKScene has a view property that should hold a reference to the SKView its contained in. So it would just be a matter of doing something like this.

    class MyScene: SKScene {
        var someView: UIView
    
        override func didMoveToView(view: SKView) {
            someView = //setup view here
            view.addSubview(someView)
        }
    }
    

    Then inside this scene you can access your UIKit objects wherever you like.