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

NSAttributedString - Underline colors are not applied correctly

我想在 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

显示this。

我预计 this。 我对它进行了 Photoshop 处理以显示我的预期:(

如何为我期望的文本添加下划线和颜色?

注意到当第一个和第三个字符具有相同的 UIColor 时会发生这种情况。但不确定为什么会这样。作为解决方法,您可以为第三个字符创建一个等于 UIColor.black 的新 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))