Swift:具有不同颜色的 AttributedString 下划线

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

我试图为 AttributedString 中的带下划线的文本提供不同的颜色。按照这个例子。

但是这段代码的结果:

        var attributedString = try AttributedString(markdown: self)
        if let rangeWord = self.slice(from: "[", to: "]") {
            let range = attributedString.range(of: rangeWord)!
            attributedString[range].underlineStyle = .single

            attributedString[range].foregroundColor = .white
            attributedString[range].underlineColor =  .green

        }

不是预想的那样

有解决办法吗?

ios swift nsattributedstring attributedstring
2个回答
3
投票

同样尝试使用

NSAttributedString

let labelString = "your label"
let textColor: UIColor = .black
let underLineColor: UIColor = .green
let underLineStyle = NSUnderlineStyle.single.rawValue

let labelAtributes:[NSAttributedString.Key : Any]  = [
    NSAttributedString.Key.foregroundColor: textColor,
    NSAttributedString.Key.underlineStyle: underLineStyle,
    NSAttributedString.Key.underlineColor: underLineColor
]

let underlineAttributedString = NSAttributedString(string: labelString,
                                                   attributes: labelAtributes)

label.attributedText = underlineAttributedString

1
投票

这对 2023 年的我来说非常有效。关键是使用“uiKit”范围。

var attributedString = try AttributedString(markdown: self)
if let rangeWord = self.slice(from: "[", to: "]") {
      let range = attributedString.range(of: rangeWord)!
      attributedString[range].foregroundColor = .white

      // notice the "uiKit" addition 
      attributedString[range].uiKit.underlineColor = .green 
      attributedString[range].uiKit.underlineStyle = .single
}
© www.soinside.com 2019 - 2024. All rights reserved.