Search code examples
swiftsprite-kitpositionsklabelnode

Why does my SKLabelNode go off the page if the score increases


So I have an SKLabelNode which displays the users high score, when the users highs score is for example 5 the labels position isn't in the same position to where it would be if the score was for example 35, or 100 makes the label go off screen, please can someone help with this issue, is there a way to make the label stay in the same position if the high score changes? do I need to put constraints on the label? BTW this is in sprite kitand using swiftHighscore label is off the screen

Highscore label isn't the same position as the other picture


Solution

  • You want to use SKLabelNodeHorizontalAlignmentMode.Left here, like this:

    class GameScene: SKScene {
    
        var label = SKLabelNode(fontNamed: "ArialMT")
    
        var score: Int = 0 {
            didSet {
                label.text = "Score: \(score)"
            }
        }
    
        override func didMoveToView(view: SKView) {
    
    
            label.fontSize = 24
            label.text = "Score: \(score)"
    
            //Place the label in upper left corner of the screen
            label.position = CGPoint(x: 50, y: CGRectGetMaxY(frame)-50)
    
            //Add this
            label.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
    
            addChild(label)
        }
    
        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
            score+=5
        }
    }
    

    The result:

    alignment mode left