Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Multi line label in Sprite Kit in Swift
// SKMultilineLabel.swift
// Created by Craig on 10/04/2015.
// Copyright (c) 2015 Interactive Coconut.
// MIT License,
/* USE:
(most component parameters have defaults)
let multiLabel = SKMultilineLabel(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", labelWidth: 250, pos: CGPoint(x: size.width / 2, y: size.height / 2))
import SpriteKit
class SKMultilineLabel: SKNode {
var labelWidth:Int {didSet {update()}}
var labelHeight:Int = 0
var text:String {didSet {update()}}
var fontName:String {didSet {update()}}
var fontSize:CGFloat {didSet {update()}}
var pos:CGPoint {didSet {update()}}
var fontColor:UIColor {didSet {update()}}
var leading:Int {didSet {update()}}
var alignment:SKLabelHorizontalAlignmentMode {didSet {update()}}
var dontUpdate = false
var shouldShowBorder:Bool = false {didSet {update()}}
//display objects
var rect:SKShapeNode?
var labels:[SKLabelNode] = []
init(text:String, labelWidth:Int, pos:CGPoint, fontName:String="ChalkboardSE-Regular",fontSize:CGFloat=10,fontColor:UIColor=UIColor.white,leading:Int? = nil, alignment:SKLabelHorizontalAlignmentMode = .center, shouldShowBorder:Bool = false)
self.text = text
self.labelWidth = labelWidth
self.pos = pos
self.fontName = fontName
self.fontSize = fontSize
self.fontColor = fontColor
self.leading = leading ?? Int(fontSize)
self.shouldShowBorder = shouldShowBorder
self.alignment = alignment
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
//if you want to change properties without updating the text field,
// set dontUpdate to false and call the update method manually.
func update() {
if (dontUpdate) {return}
if (labels.count>0) {
for label in labels {
labels = []
let separators = NSCharacterSet.whitespacesAndNewlines
let words = (text as NSString).components(separatedBy: separators)
var finalLine = false
var wordCount = -1
var lineCount = 0
while (!finalLine) {
var lineLength = CGFloat(0)
var lineString = ""
var lineStringBeforeAddingWord = ""
// creation of the SKLabelNode itself
let label = SKLabelNode(fontNamed: fontName)
// name each label node so you can animate it if u wish = "line\(lineCount)"
label.horizontalAlignmentMode = alignment
label.fontSize = fontSize
label.fontColor = fontColor
while lineLength < CGFloat(labelWidth)
if wordCount > words.count-1
//label.text = "\(lineString) \(words[wordCount])"
finalLine = true
lineStringBeforeAddingWord = lineString
lineString = "\(lineString) \(words[wordCount])"
label.text = lineString
lineLength = label.frame.width
if lineLength > 0 {
if (!finalLine) {
lineString = lineStringBeforeAddingWord
label.text = lineString
var linePos = pos
if (alignment == .left) {
linePos.x -= CGFloat(labelWidth / 2)
} else if (alignment == .right) {
linePos.x += CGFloat(labelWidth / 2)
linePos.y += CGFloat(-leading * lineCount)
label.position = CGPoint(x:linePos.x , y:linePos.y )
labelHeight = lineCount * leading
func showBorder() {
if (!shouldShowBorder) {return}
if let rect = self.rect {
self.removeChildren(in: [rect])
self.rect = SKShapeNode(rectOf: CGSize(width: labelWidth, height: labelHeight))
if let rect = self.rect {
rect.strokeColor = UIColor.white
rect.lineWidth = 1
rect.position = CGPoint(x: pos.x, y: pos.y - (CGFloat(labelHeight) / 2.0))
Copy link

rtonev commented Jul 25, 2015

Your label looks pretty good. Can you please write what the license for the code is?

Copy link

kevinwo commented Sep 24, 2015

I've forked and updated this gist to be multi-platform (i.e. work with OS X and tvOS), and cleaned up a bit to play nice with Swift 2:

Copy link

klappy commented Nov 22, 2015

Since my usage needed to obey line breaks \n, I updated the code with a few simple changes.
I forked @kevinwo's and added necessary changes.

Copy link

I have made an update with the following:

  • Added MIT license
  • Swift 3.0 syntax
  • If you don't pass in a leading, leading now defaults to font size
  • Added required init, fixed small bugs

Copy link

krodak commented Nov 30, 2016

I've updated your code with small visual fixes:

  • removing parenthesis when using if and while as it's not needed in Swift
  • extracted 2 small functions from update() to comply to standard SwiftLint configuration
  • replaced initial if in every function with guard

Copy link

I'm impressed. I think you should use SKColor as opposed to UIColor, though.

Copy link

Ufosek commented Aug 5, 2017

Strange things happens when you set fontSize bigger then 12 - sometimes text is cut or it crashes because of infinite loop (lineCount increments constantly).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment