Home > Mobile >  Swift: AttributedString underline with different color
Swift: AttributedString underline with different color

Time:05-23

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?

CodePudding user response:

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
  • Related