Created
April 29, 2017 09:56
-
-
Save zoejessica/c88bf0d62b003ec687a762bcbc050189 to your computer and use it in GitHub Desktop.
Multiline SKLabelNode in Swift 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from https://oleb.net/blog/2016/08/swift-3-strings/ | |
extension String { | |
func wrapped(after: Int) -> [String] { | |
var i = 0 | |
let lines = self.characters.split(omittingEmptySubsequences: false) { character in | |
switch character { | |
case "\n", | |
" " where i >= after: | |
i = 0 | |
return true | |
default: | |
i += 1 | |
return false | |
} | |
}.map(String.init) | |
return lines | |
} | |
} | |
// adapted from https://github.com/benmorrow/Multiline-SpriteKit-Label/blob/master/MultilinedSKLabelNode/SKLabelNode%2BExtensions.swift | |
extension SKLabelNode { | |
func multiline(length: Int) -> SKLabelNode? { | |
guard let text = text else { return nil } | |
let substrings = text.wrapped(after: length) | |
return substrings.enumerated().reduce(SKLabelNode()) { | |
let label = SKLabelNode(fontNamed: self.fontName) | |
label.text = $1.element | |
label.fontColor = self.fontColor | |
label.fontSize = self.fontSize | |
label.position = self.position | |
label.horizontalAlignmentMode = self.horizontalAlignmentMode | |
label.verticalAlignmentMode = self.verticalAlignmentMode | |
let height = self.fontSize | |
let y = (height / 2) + CGFloat($1.offset - substrings.count / 2) * height | |
label.position = CGPoint(x: self.position.x, y: self.position.y - y) | |
$0.addChild(label) | |
return $0 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment