HTML text with underline has unexpected appearance with attributed string in version iOS 14

I am trying to use the HTML as the content of UILabel but getting a weird issue in iOS 14 that the underline color is getting changed as per the text color.

I am using the following code

  1. ViewDidLoad

Code Block
override func viewDidLoad() {
super.viewDidLoad()
lblHtml2.htmlText = """
<p><span style="text-decoration:underline">I am facing<span style="color:blue;font-weight:bold"> error </span>in version <span style="color:darkolivegreen;font-weight:bold">of greater than 14 </span> for wrong underline color.</span></p>
"""
}


I am using this extension to format the HTML into an attributed string:
Code Block
extension UILabel {
var htmlText: String? {
get {
do {
if let attrText = attributedText {
let data = try attrText.data(from: NSRange(location: 0, length: attrText.length),
documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html])
return String(data: data, encoding: .utf8)
}
} catch {
// Fall through
}
return text
}
set {
guard let html = newValue, !html.isEmpty else {
self.text = nil
return
}
do {
let attributedString = try html.htmlToAttributedString(pointSize: font.pointSize, color: textColor, direction: "rtl")
self.attributedText = attributedString
} catch {
self.text = html
}
}
}
}




Code Block

Code Block
extension String {
enum Errors: Error {
case AttributedStringConversionError
}
func htmlToAttributedString(pointSize: CGFloat = UIFont.labelFontSize, color: UIColor = .black, direction: String = "ltr") throws -> NSAttributedString {
let fontedHTML = #"""
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="UTF-8">
<style>
rt {
display: inline
}
body {
font-size: \#(pointSize)px;
font-family: 'system-ui';
color: \#(fontColor(color: color));
}
</style>
</head>
<body>
<div dir="\#(direction)">\#(self)</div>
</body>
</html>
"""#
let data = Data(fontedHTML.utf8)
guard let attrText = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
throw Errors.AttributedStringConversionError
}
if !attrText.string.isEmpty && attrText.string.hasSuffix("\n") {
return attrText.attributedSubstring(from: NSRange(location: 0, length: attrText.length - 1))
} else {
return attrText
}
}
private func fontColor(color: UIColor) -> String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return "rgba(\(Int(red * 255)), \(Int(green * 255)), \(Int(blue * 255)), \(alpha))"
}
}

Code Block


correct display in iOS 13 but incorrect display in iOS14

HTML text with underline has unexpected appearance with attributed string in version iOS 14
 
 
Q