我需要我的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
这只会导致第一个角色消失。 referencedString的print语句看起来像这样(显然是正确的):
■{NSForegroundColor = "UIExtendedSRGBColorSpace 1 0 0 1";} restOfText{}
我究竟做错了什么?
问题是长度为1的NSRange
值。对于Swift字符串,使用专用的NSRange
初始化器,取String.Index
范围和目标字符串
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。哎呦