I have some HTML content which i want to render in my native UILabel, but in addition to that i have to add custom font to that UILabel. I am using NSAttributedString to do that and using following code to render HTML content in my UILabel.
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: .utf16, allowLossyConversion: false) else {
return nil
}
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
let attributes = [
NSForegroundColorAttributeName: UIColor.lightGray,
NSFontAttributeName : UIFont.systemFont(ofSize: 12)
]
html.setAttributes(attributes, range: NSRange(0..<html.length))
return html
}
var str = "Here is the <bold>string</bold> that i want to be bold.
messageLabel.attributedText = str.htmlAttributedString()
The problem here is that when i apply font attributes on the HTML rendered attributed string. Then all the HTML formatting like bold is lost.
So is there a way that i can apply some selected font on HTML rendered attributed string