Swift:NSMutableAttributedString foregroundColor设置不正确

问题描述 投票:0回答:2

我需要我的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{}

我究竟做错了什么?

swift nsattributedstring
2个回答
1
投票

问题是长度为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 ))

0
投票

编写的代码没有问题。我后来不小心覆盖了cell.label.text。哎呦

© www.soinside.com 2019 - 2024. All rights reserved.