NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to integrate SpriteKit using SpriteView

Paul Hudson    @twostraws   

Updated for Xcode 12.0

New in iOS 14

SwiftUI’s SpriteView lets us render any SKScene subclass right inside SwiftUI, although you do need to be careful to either create your scene from an SKS file that declares a size, or to specify a size yourself.

To try it out, first add import SpriteKit to your Swift file.

Second, create some sort of game scene you want to render. For example, this will create falling boxes wherever you tap, adding a physics effect so they interact neatly:

class GameScene: SKScene {
    override func didMove(to view: SKView) {
        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        let box = SKSpriteNode(color: UIColor.red, size: CGSize(width: 50, height: 50))
        box.position = location
        box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
        addChild(box)
    }
}

Third, create your game scene somewhere, making sure to give it a specific size. Mine is being created programmatically, so I’m giving it a precise size of 300x400 points:

struct ContentView: View {
    var scene: SKScene {
        let scene = GameScene()
        scene.size = CGSize(width: 300, height: 400)
        scene.scaleMode = .fill
        return scene
    }

    var body: some View {
        // more code here
    }
}

And now you can create a SpriteView inside your body property, using that game scene:

SpriteView(scene: scene)
    .frame(width: 300, height: 400)
    .edgesIgnoringSafeArea(.all)

The game scene you create is fully interactive, so it works just like a regular SKView would do in UIKit.

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5

Link copied to your pasteboard.