Display Background with SpriteKit iOS Tutorial

Sprite Kit provides a hardware-accelerated animation system which has been optimized for creating 2D games. In this tutorial we will use the Game template in Xcode to add a background image. This tutorial is made with Xcode 8.2.1 and built for iOS 10.2.

Open Xcode and choose iOS -> Application -> Game

For product name, use SpriteKitBackgroundTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and SpriteKit as Game Technology. Also make sure only iPhone is selected in Devices.

We need a background for this tutorial so download our image and add it to the project. Make sure you select the "Copy items if needed" option

In Xcode's Game template, a lot of initial work is already been done. In Sprite Kit, a scene controls each “screen” of your app. Navigate to the GameViewController.swift file and in the GameViewController class the viewDidLoad method is defined. Here the scene is created and the Gamescene object is presented. Change the viewDidLoad method to 

override func viewDidLoad() {
    let scene = GameScene(size:CGSize(width: 1080, height: 1920))
    let skView = self.view as! SKView
    scene.scaleMode = .aspectFill

Go to the GameScene.swift file. Here the GameScene class is defined. In the didMove method the custom code is implemented. Delete all code inside the GameScene class and add the didMove method

class GameScene: SKScene {
    override func didMove(to view: SKView) {
        let background = SKSpriteNode(imageNamed: "background.jpg")
        background.position = CGPoint(x: size.width/2, y: size.height/2)

Sprite Kit has a special class to create and manipulate sprites called SKSpriteNode. In this node our image is loaded. Next, the image is added to our scene. Finally, delete the GameScene.sks and Action.sks files from the project as these are no more needed.

Build and Run the project.

You can download the source code of the SpriteKitBackgroundTutorial at the ioscreator repository on github.