Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
Fattie Avatar asked Apr 29 '18 01:04

Fattie


2 Answers

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
like image 139
Martin Škorc Avatar answered Oct 24 '22 12:10

Martin Škorc


Following up - I posted a link instead of code, which is kind of a no-no. I don't have a big rep (noob), so I also can't edit yet :)

I recently discovered that you can overlay UIKit on top of scenekit (probably Sprite Kit too). I've tried it and it works with no loss in FPS, so I'm removing all of my Spritekit overlays (menus/labels) and using the UIKit basics (UIButton, UILabel). If this is of interest, I can share some code. I'm still figuring things out, but far enough into it that I think it's going to work.

like image 37
Voltan Avatar answered Oct 24 '22 11:10

Voltan