【问题标题】:Applying different colors to certain parts of SKLabelNode's text对 SKLabelNode 文本的某些部分应用不同的颜色
【发布时间】:2015-08-04 19:42:31
【问题描述】:

我很确定不能使用 NSMutableAttributedStringNSAttributedString。我试过的是:

 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 是一种解决方案,但我不能说它很优雅(或高效)。

【问题讨论】:

    标签: objective-c sprite-kit nsattributedstring sklabelnode


    【解决方案1】:

    我在 GitHub 上找到了您可能感兴趣的内容。它是用 Swift 编写的,但代码很短,应该很容易理解。

    ASAttributedLabelNode

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 感谢您的回复。是的,我可以看到没有这样的效果,但实际上我很感兴趣有没有办法用 SKLabelNode 来完成这个......你对如何做到这一点有一些想法吗?
      • 由于字体是由其名称设置的,并且文本本身只能通过副本访问,所以看起来在 SpriteKit 会根据需要操纵文本而不是在幕后发生一些事情以任何方式确认属性文本。如果您真的想这样做,您可能可以使用NSAttributedStringtext 属性子类化SKNode 以替换SKLabelNode
      • Fennelouski 如果您可以为此编写一个示例,即使使用伪代码也将非常好。如果没有,那么这不是问题:) 无论如何,我会赞成你指出有用信息的答案。
      【解决方案3】:

      在 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
      

      【讨论】:

        【解决方案4】:

        从 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;
        

        【讨论】:

        • 值得注意的是,并非所有属性键似乎都有效。彩色的当然可以,所以这个答案非常有效,但我发现既没有下划线也没有删除线功能。
        猜你喜欢
        • 1970-01-01
        • 2011-09-03
        • 2014-09-26
        • 1970-01-01
        • 2012-12-28
        • 1970-01-01
        • 2016-10-11
        • 1970-01-01
        • 2014-05-21
        相关资源
        最近更新 更多