swiftsprite-kitswift4sklabelnode

Swift 4 SKLabelNode not appearing


I have been trying for a while to display a simple SKLabelNode, with no luck. I have tried many different ways, with mixed results. This is what I have currently, but nothing shows up:

func layoutMenu() {
    let appNameLabel = SKLabelNode()
    appNameLabel.text = "HI"
    appNameLabel.zPosition = 1000
    appNameLabel.fontColor = SKColor.red
    appNameLabel.position = CGPoint(x:0.5, y:0.5)
    self.addChild(appNameLabel)
}

I call this function in the didMove() function. By mixed results, I mean that sometimes the label's red color shows up in a blurry block (no text though). This was only achieved using the alignment properties, which I would prefer not to use.

Edit: some info about the frames which may be useful.

The root skscene frame:

▿ (-0.0, -0.0, 1.0, 1.0)
  ▿ origin : (-0.0, -0.0)
    - x : -0.0
    - y : -0.0
  ▿ size : (1.0, 1.0)
    - width : 1.0
    - height : 1.0

And the SKLabelNode:

▿ (-11.5, 0.5, 25.0, 25.0)
  ▿ origin : (-11.5, 0.5)
    - x : -11.5
    - y : 0.5
  ▿ size : (25.0, 25.0)
    - width : 25.0
    - height : 25.0

Solution

  • I think the problem is related to the SKScene's frame, which has size of (1,1). In order to understand how to setup label+scene, you may try the following code on Playground:

    import SpriteKit
    import PlaygroundSupport
    
    let frame = CGRect(x: 0, y: 0, width: 200, height: 200)
    let view = SKView(frame: frame)
    let scene = SKScene(size: frame.size)
    view.presentScene(scene)
    scene.backgroundColor = UIColor.white
    PlaygroundPage.current.liveView = view
    
    let label = SKLabelNode()
    label.text = "mylabel"
    label.fontColor = SKColor.black
    label.position = CGPoint(x:frame.size.width / 2.0, y:frame.size.height / 2.0)
    scene.addChild(label)
    

    the result is:

    enter image description here