3

我很确定不能为此使用NSMutableAttributedStringand 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是解决方案,但我不能说它是优雅的(或高性能的)。

4

4 回答 4

4

我在 GitHub 上发现了一些你可能感兴趣的东西。它在 Swift 中,但代码很短,应该很容易理解。

ASAttributedLabelNode

于 2015-08-04T23:01:37.663 回答
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
于 2017-12-09T21:30:23.300 回答
2

SKLabelNode不支持NSAttributedStringNSMutableAttributedString。当您使用时,labelNode.text = [newString string]您只使用属性字符串的文本部分并忽略您在前几行中所做的所有更改。

于 2015-08-04T20:00:05.727 回答
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;
于 2017-12-04T17:39:58.310 回答