Swift:NSMutableAttributedString foregroundColor未正确设置

Swift:NSMutableAttributedString foregroundColor未正确设置,swift,nsattributedstring,Swift,Nsattributedstring,我需要UILabel的第一个字符的颜色与标签的其余部分不同。我正在使用以下代码: let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: cell.label.text!) attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, ra

我需要UILabel的第一个字符的颜色与标签的其余部分不同。我正在使用以下代码:

        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: cell.label.text!)
        attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 1))
        cell.label.attributedText = attributedString
这只会导致第一个角色消失。attributedString的打印语句如下所示:

■{NSForegroundColor = "UIExtendedSRGBColorSpace 1 0 0 1";} restOfText{}
我做错了什么?

问题是长度为1的NSRange值。对于Swift字符串,使用专用的NSRange初始值设定项,获取字符串.索引范围和目标字符串

let string = cell.label.text!
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: string)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(...string.startIndex, in: string ))

编写的代码没有问题。后来我意外地重写了cell.label.text。哇

谢谢,但你的代码结果与我的代码结果完全相同。我在一个操场上做了一个快速测试,得到了预期的结果redI中的第一个字符肯定有其他问题。。。我不明白为什么指定范围内的字符串部分消失了。@CollinBell此代码比您的代码更正确。您的代码将因大多数表情符号而失败。@Larme请尝试让string=HelI在tableview单元格中运行您的代码,它完全按照我的预期工作。是否可能在其他位置重置了属性?是否检查了UILabel约束。是否可以显示debugPrintcell.label.text!的结果@简:是的,你是对的。我是一个白痴,在函数后面重写了整个cell.label.text。谢谢你提醒我重新评估。没问题!很高兴你发现了这个问题!