NSAttributedString -下划线颜色未正确应用



我想在UILabel中为文本添加下划线和颜色。下划线和文本具有复杂的变化颜色模式,但我的代码有时会出错。

下面的最小代码重现了这个问题。

let attributedTitle = NSMutableAttributedString(string: "ABC")
attributedTitle.addAttributes([
.foregroundColor: UIColor.black,
.underlineColor: UIColor.black,
.underlineStyle: NSUnderlineStyle.single.rawValue,
],
range: NSRange(location: 0, length: 1))
attributedTitle.addAttributes([
.foregroundColor: UIColor.yellow,
.underlineColor: UIColor.yellow,
.underlineStyle: NSUnderlineStyle.single.rawValue,
],
range: NSRange(location: 1, length: 1))
attributedTitle.addAttributes([
.foregroundColor: UIColor.black,
.underlineColor: UIColor.black,
.underlineStyle: NSUnderlineStyle.single.rawValue,
],
range: NSRange(location: 2, length: 1))
let label = UILabel()
label.attributedText = attributedTitle

显示如下。

我预料到这一点。我把它ps了一下,以显示我所期望的:(

如何下划线和颜色的文本,我的期望?

请注意,当第一个和第三个字符具有相同的UIColor时,会发生这种情况。但不确定为什么会这样。作为一种变通方法,您可以创建一个新的UIColor等于UIColor。

let attributedTitle = NSMutableAttributedString(string: "ABC")
attributedTitle.addAttributes([
.foregroundColor: UIColor.black,
.underlineColor: UIColor.black,
.underlineStyle: NSUnderlineStyle.single.rawValue,
],
range: NSRange(location: 0, length: 1))
attributedTitle.addAttributes([
.foregroundColor: UIColor.systemYellow,
.underlineColor: UIColor.systemYellow,
.underlineStyle: NSUnderlineStyle.single.rawValue,
],
range: NSRange(location: 1, length: 1))
attributedTitle.addAttributes([
.foregroundColor: UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0),
.underlineColor: UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0),
.underlineStyle: NSUnderlineStyle.single.rawValue,
],
range: NSRange(location: 2, length: 1))

最新更新