我非常确定,因此无法使用NSMutableAttributedString
和NSAttributedString
。我尝试过的是:
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];
这不起作用,文字仍然具有原始颜色。有没有办法用SKLabelNode
执行此操作?使用多个SKLabelNodes
是解决方案,但我不能说它优雅(或高效)。
答案 0 :(得分:4)
我在GitHub上发现了一些你可能感兴趣的东西。它在Swift中,但代码很短,应该很容易理解。
答案 1 :(得分:2)
SKLabelNode
不支持NSAttributedString
或NSMutableAttributedString
。当您使用labelNode.text = [newString string]
时,您只获取属性字符串的文本部分,并忽略您在前一行中所做的所有更改。
答案 2 :(得分:2)
在Swift 4中:
let newString = NSMutableAttributedString(string: "firstsecondthird")
newString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSMakeRange(0,5))
newString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.green, range: NSMakeRange(5,6))
newString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(11,5))
labelNode.attributedText = newString
答案 3 :(得分:1)
从iOS 11开始,SKLabelNode支持NSAttributedStrings,因此不再需要ASAttributedLabelNode。您的代码如下:
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;