Search code examples
iosswiftsprite-kitswift2skscene

SKLabelNode not being created in SKScene – Swift


In the title screen of my SpriteKit game, I want to have an SKLabelNode display "Play". When I run the code below, however, the node is not added to the scene.

import UIKit
import SpriteKit

class TitleScreen: SKScene {

var title: SKLabelNode!

override func didMoveToView(view: SKView) {

    backgroundColor = SKColor(colorLiteralRed: 0.4, green: 0.835, blue: 1, alpha: 1)

    //The color is a light blue, so the node should not be hidden by the color of the screen.

    title = SKLabelNode()
    title.text = "Play"
    title.color = SKColor.blackColor()
    title.fontSize = 70

    self.addChild(title)

}

What should I do to make this work?


Solution

  • You haven't set correctly the position of the label, so it is probably off screen. Your code works for me. Try this:

    override func didMoveToView(view: SKView) {
    
            backgroundColor = SKColor(colorLiteralRed: 0.4, green: 0.835, blue: 1, alpha: 1)
    
            //The color is a light blue, so the node should not be hidden by the color of the screen.
    
            title = SKLabelNode()
            title.position = CGPoint(x: frame.midX, y: frame.midY)
            title.text = "Play"
            title.color = SKColor.blackColor()
            title.fontSize = 70
    
            self.addChild(title)
        }
    

    Note that when scene is loaded from .sks file it has a default size of 1024x768. If you want to change that, set scene's size on its creation explicitly .If you want to match the view's size, you can do something like this:

    scene.size = yourSkView.bounds.size