Search code examples
iossprite-kitsknode

SKLabelNode - how to center align when more than one line?


With SKLabelNode, it would appear that when you break to more than one line,

the results is always

abcde
fg

rather than

abcde
 fg

Really it seems that SKLabelNode is just left-aligned, and that's it.

Is there a solution - how to make multiline SKLabelNode center-align?


Note - horizontalAlignmentMode is totally unrelated. it simply allows you to choose whether the anchor of the overall label area is on the left, right or center of the position.


Solution

  • I solved this issue by setting attributedText to SKLabelNode. Seemed like the easiest way to do it, hope Apple fixes this issue soon.

    Swift 4

    let attrString = NSMutableAttributedString(string: yourString)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    let range = NSRange(location: 0, length: yourString.count)
    attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: range)
    attrString.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.black, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 30)], range: range)
    yourLabelNode.attributedText = attrString