Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Display HTML data in a label or textView

I have some HTML data, which contains headings, paragraphs , images and lists tags.

Is there a way to display this data in one UITextView or UILabel?

like image 791
Talha Ahmad Khan Avatar asked May 05 '16 10:05

Talha Ahmad Khan


People also ask

How do I display HTML content in Swift?

Show activity on this post. extension String { var htmlToAttributedString: NSAttributedString? { guard let data = self. data(using: . utf8) else { return nil } do { return try NSAttributedString(data: data, options: [ NSAttributedString.

How do you display HTML formatted text in UILabel Swift?

To render this text properly in UILabel or UITextView, you need to convert it to NSAttributedString . NSAttributedString has built-in support for this conversion. First, we need to convert HTML string to Data . let htmlString = "This is a <b>bold</b> text."

What is swift HTML?

🗺 swift-html. A Swift DSL for type-safe, extensible, and transformable HTML documents.


2 Answers

For Swift 5:

extension String {     var htmlToAttributedString: NSAttributedString? {         guard let data = data(using: .utf8) else { return nil }         do {             return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)         } catch {             return nil         }     }     var htmlToString: String {         return htmlToAttributedString?.string ?? ""     } } 

Then, whenever you want to put HTML text in a UITextView use:

textView.attributedText = htmlText.htmlToAttributedString 
like image 123
Roger Carvalho Avatar answered Sep 19 '22 16:09

Roger Carvalho


Here is a Swift 3 version:

private func getHtmlLabel(text: String) -> UILabel {     let label = UILabel()     label.numberOfLines = 0     label.lineBreakMode = .byWordWrapping     label.attributedString = stringFromHtml(string: text)     return label }  private func stringFromHtml(string: String) -> NSAttributedString? {     do {         let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)         if let d = data {             let str = try NSAttributedString(data: d,                                              options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],                                              documentAttributes: nil)             return str         }     } catch {     }     return nil } 

I found issues with some of the other answers here and it took me a bit to get this right. I set the line break mode and number of lines so that the label sized appropriately when the HTML spanned multiple lines.

like image 45
garie Avatar answered Sep 18 '22 16:09

garie