How to display html formatted text in ios label

hap497 picture hap497 · Sep 17, 2014 · Viewed 55.3k times · Source

I would like to display html formatted text on a UILabel in IOS.

In Android, it has api like this .setText(Html.fromHtml(somestring));

Set TextView text from html-formatted string resource in XML

I would like to know what / if there is an equivalent in ios?

I search and find this thread:

How to show HTML text from API on the iPhone?

But it suggests using UIWebView. I need to display html formatted string in each table cell, so I think have 1 webview per row seems a bit heavy.

Is that any other alternative?

Thank you.

Answer

ƒernando Valle picture ƒernando Valle · Nov 16, 2016

Swift 3.0

do {
    let attrStr = try NSAttributedString(
        data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)
    label.attributedText = attrStr
} catch let error {

}