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
?
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.
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."
🗺 swift-html. A Swift DSL for type-safe, extensible, and transformable HTML documents.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With