Skip to content

Instantly share code, notes, and snippets.

@klappy
Forked from kevinwo/SKMultilineLabel.swift
Last active October 11, 2017 03:21
Show Gist options
  • Save klappy/8cd81068f066b6e36f44 to your computer and use it in GitHub Desktop.
Save klappy/8cd81068f066b6e36f44 to your computer and use it in GitHub Desktop.
Multi line label in Sprite Kit in Swift
//
// SKMultilineLabel.swift
//
// Created by Craig on 10/04/2015
// Modified by Christopher Klapp on 11/21/2015 for line breaks \n for paragraphs
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
/* 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))
self.addChild(multiLabel)
*/
import SpriteKit
class SKMultilineLabel: SKNode {
//props
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:SKColor {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:SKColor=SKColor.blackColor(),leading:Int=10, 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
self.shouldShowBorder = shouldShowBorder
self.alignment = alignment
super.init()
self.update()
}
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 {
label.removeFromParent()
}
labels = []
}
let separators = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let lineSeparators = NSCharacterSet.newlineCharacterSet()
let paragraphs = text.componentsSeparatedByCharactersInSet(lineSeparators)
var lineCount = 0
for (_, paragraph) in paragraphs.enumerate() {
let words = paragraph.componentsSeparatedByCharactersInSet(separators)
var finalLine = false
var wordCount = -1
while (!finalLine) {
lineCount++
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
label.name = "line\(lineCount)"
label.horizontalAlignmentMode = alignment
label.fontSize = fontSize
label.fontColor = SKColor.whiteColor()
while lineLength < CGFloat(labelWidth)
{
wordCount++
if wordCount > words.count-1
{
//label.text = "\(lineString) \(words[wordCount])"
finalLine = true
break
}
else
{
lineStringBeforeAddingWord = lineString
lineString = "\(lineString) \(words[wordCount])"
label.text = lineString
lineLength = label.frame.size.width
}
}
if lineLength > 0 {
wordCount--
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 = CGPointMake( linePos.x , linePos.y )
self.addChild(label)
labels.append(label)
//println("was \(lineLength), now \(label.width)")
}
}
}
labelHeight = lineCount * leading
showBorder()
}
func showBorder() {
if (!shouldShowBorder) {return}
if let rect = self.rect {
self.removeChildrenInArray([rect])
}
self.rect = SKShapeNode(rectOfSize: CGSize(width: labelWidth, height: labelHeight))
if let rect = self.rect {
rect.strokeColor = SKColor.whiteColor()
rect.lineWidth = 1
rect.position = CGPoint(x: pos.x, y: pos.y - (CGFloat(labelHeight) / 2.0))
self.addChild(rect)
}
}
}
@endavid
Copy link

endavid commented Jan 10, 2016

I think this line,
label.fontColor = SKColor.whiteColor()

should be
label.fontColor = self.fontColor

Apart from that, there's an out-of-memory bug in the original code. Check comments in https://gist.github.com/kevinwo/0e83ec5245126db172a9

@HowardTheDuck007
Copy link

Version converted for Swift3. Thank you!!

//
// SKMultilineLabel.swift
//
// Created by Craig on 10/04/2015
// Modified by Christopher Klapp on 11/21/2015 for line breaks \n for paragraphs
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
/* 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))
self.addChild(multiLabel)

*/

import SpriteKit

class SKMultilineLabel: SKNode {
//props
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:SKColor {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:SKColor=SKColor.black,leading:Int=10, 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
    self.shouldShowBorder = shouldShowBorder
    self.alignment = alignment
    
    super.init()
    
    self.update()
}

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 {
            label.removeFromParent()
        }
        labels = []
    }
    let separators = NSCharacterSet.whitespacesAndNewlines
    let lineSeparators = NSCharacterSet.newlines
    let paragraphs = text.components(separatedBy: lineSeparators)
//    let paragraphs = text.componentsSeparatedByCharactersInSet(lineSeparators)

    var lineCount = 0
    for (_, paragraph) in paragraphs.enumerated() {
        let words = paragraph.components(separatedBy: separators)
        var finalLine = false
        var wordCount = -1
        while (!finalLine) {
            lineCount += 1
            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
            label.name = "line\(lineCount)"
            label.horizontalAlignmentMode = alignment
            label.fontSize = fontSize
            label.fontColor = SKColor.white
            
            while lineLength < CGFloat(labelWidth)
            {
                wordCount += 1
                if wordCount > words.count-1
                {
                    //label.text = "\(lineString) \(words[wordCount])"
                    finalLine = true
                    break
                }
                else
                {
                    lineStringBeforeAddingWord = lineString
                    lineString = "\(lineString) \(words[wordCount])"
                    label.text = lineString
                    lineLength = label.frame.size.width
                }
            }
            if lineLength > 0 {
                wordCount -= 1
                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 = CGPointMake( linePos.x , linePos.y )
                label.position = CGPoint(x: linePos.x , y: linePos.y )
                self.addChild(label)
                labels.append(label)
                //println("was \(lineLength), now \(label.width)")
            }
        }
    }
    labelHeight = lineCount * leading
    showBorder()
}

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 = SKColor.white
        rect.lineWidth = 1
        rect.position = CGPoint(x: pos.x, y: pos.y - (CGFloat(labelHeight) / 2.0))
        self.addChild(rect)
    }
}

}

@klappy
Copy link
Author

klappy commented Feb 6, 2017

@HowardTheDuck007: Do you mind forking the Gist and revising with your Swift 3 updates? I'll take a look and incorporate to help others that come across this.

Thanks!

@klappy
Copy link
Author

klappy commented Feb 6, 2017

@endavid: Thanks for pointing out the issue that would be encountered with words exceeding the line.

As far as the Japanese and other languages that need broken up by something other than spaces, tokenization is a fun subject that would address the issue. I don't have the time right now to jump into tokenization in swift but I have done extensive work in tokenization for many languages in other programming languages such as ruby and javascript. One overly simplistic approach is splitting on posix based non unicode word character classes. In JavaScript I use the XRegexp library that adds unicode support to JS. The regex I commonly use for tokenization is splitting on XRegexp('[^\\pL\\pM]+?') Japanese and other Asian languages sometimes require a dictionary approach to tokenization. Hope that is helpful.

@ducky007
Copy link

Your label is being created always as white. I suggest changing label.fontColor = SKColor.white to label.fontColor = self.fontColor

@doroboneko
Copy link

Hi, great code, it's a pity there is no text field in Sprite Kit :-(
You can directly ask for CharacterSet.whitespacesAndNewlines in Swift String, no need to call for NS.

let separators = CharacterSet.whitespacesAndNewlines
let words = line.components(separatedBy: separators)

And you can ask too for line in Swift with enumerateLines, no NS needed

var lines: [String] {
        var result: [String] = []
        enumerateLines { line, _ in result.append(line) }
        return result
    }

I would suggest to add (* 0.13) to leading to have line-height of 13% otherwise the lines are too close, "p" character would touch the characters at next line for example.

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