Swift: AttributedString underline with different color

606 Views Asked by At

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?

2

There are 2 best solutions below

0
Mr.SwiftOak On BEST ANSWER

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
0
Bogdan Farca On

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
}