1

I'm trying to give different color for underlined text in the AttributedString. as per this example.

enter image description here

But the result with this snippet of code:

        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

        }

Is not what is expected

enter image description here

Is there a workaround it?

Mohamed Emad Hegab
  • 2,665
  • 6
  • 39
  • 64

2 Answers2

3

Try using NSAttributedString likewise:

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
Mr.SwiftOak
  • 1,469
  • 3
  • 8
  • 19
1

The key is to use the uiKit scope.

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
}
Bogdan Farca
  • 3,856
  • 26
  • 38