Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
Yonny Avatar asked Sep 26 '22 11:09

Yonny


2 Answers

  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.

like image 121
Beau Nouvelle Avatar answered Oct 16 '22 21:10

Beau Nouvelle


If you create a new Spritekit application, it will have the view controller already set up for what you need. All you need to do is copy that view controller into your project, apply the segue, and you will be good to go with working with skscene.

to answer your question on UIKit, yes you can place UIKit elements on top of a SKScene, it will of course only be attacked to the view that the skscene is a part of, so the scene itself cannot directly interact with them, you would need to implement some kind of messaging system so the two can communicate.

like image 1
Knight0fDragon Avatar answered Oct 16 '22 21:10

Knight0fDragon