0
votes

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

1
@UmaMadhavi your link worked for me. thanksMadu

1 Answers

0
votes

Replace the font according to your requirement.

func htmlAttriButedText(str : String) -> NSAttributedString{
        let attrStr = try! NSMutableAttributedString(
            data: str.data(using: String.Encoding.utf8, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
        attrStr.addAttribute(NSForegroundColorAttributeName, value: lightTextColor, range: NSMakeRange(0, attrStr.length))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 13), range: NSMakeRange(0, attrStr.length))
        return attrStr
    }