Swift version: 5.6
The SKLabelNode
class is a fast and efficient way to draw text in SpriteKit games. To use it, first create a property in your game scene:
var scoreLabel: SKLabelNode!
Now create the label node by telling it want font use, its alignment, and also an initial text value if you want one. This code creates a label node using the Chalkduster font, places it in the top-right corner of the screen, and gives it the initial text "Score: 0":
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.text = "Score: 0"
scoreLabel.horizontalAlignmentMode = .right
scoreLabel.position = CGPoint(x: 980, y: 700)
addChild(scoreLabel)
With that score label in place, you can now create a score
integer property to store the actual number of a player's score, then use a property observer to modify the label whenever the score changes:
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 7.0 – see Hacking with Swift tutorial 11
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.