objective-csprite-kitnsattributedstringsklabelnode

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).


Solution

  • As of iOS 11, SKLabelNode supports NSAttributedStrings, so ASAttributedLabelNode should no longer be necessary. Your code would look like:

    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.attributedText = newString;