Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying different colors to certain parts of SKLabelNode's text

I am pretty much sure that for this can't be used NSMutableAttributedString and NSAttributedString. What I've tried is:

 NSMutableAttributedString * newString = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

labelNode.text = [newString string];

This doesn't work and text still has it's original color. Is there any way to do this with SKLabelNode ? Using multiple SKLabelNodes is solution, but I can't say it's elegant (or performant).

like image 964
Whirlwind Avatar asked Dec 13 '25 11:12

Whirlwind


2 Answers

I found something that may interest you on GitHub. It's in Swift but code is very short and should be easily comprehensible.

ASAttributedLabelNode

like image 58
Dominique Vial Avatar answered Dec 15 '25 09:12

Dominique Vial


SKLabelNode does not support NSAttributedString or NSMutableAttributedString. When you use labelNode.text = [newString string] you're taking just the text portion of the attributed string and ignoring all of the changes you made in the previous lines.

like image 43
Fennelouski Avatar answered Dec 15 '25 08:12

Fennelouski