There are a range of ways to display HTML text in SwiftUI. However I found some issues to use them. Interfacing UILabel
and using NSAttributedText
only enable us to display small size string moreover WKWebView
restrict to use desirable font. Considering all of these, I found using UITextView
with NSAttributedText
is more convenient to display HTML text in SwiftUI. The code is following
import UIKit
import SwiftUI
struct HTMLFormattedText: UIViewRepresentable {
let text: String
private let textView = UITextView()
init(_ content: String) {
self.text = content
}
func makeUIView(context: UIViewRepresentableContext<Self>) -> UITextView {
textView.widthAnchor.constraint(equalToConstant:UIScreen.main.bounds.width).isActive = true
textView.isSelectable = false
textView.isUserInteractionEnabled = false
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isScrollEnabled = false
return textView
}
func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<Self>) {
DispatchQueue.main.async {
if let attributeText = self.converHTML(text: text) {
textView.attributedText = attributeText
} else {
textView.text = ""
}
}
}
private func converHTML(text: String) -> NSAttributedString?{
guard let data = text.data(using: .utf8) else {
return nil
}
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return attributedString
} else{
return nil
}
}
}
struct ContentView: View {
var body: some View {
HTMLFormattedText("<p>Danish-made 1st class kebab</p><p><br></p><p>Say yes thanks to 2kg. delicious kebab, which is confused and cooked.</p><p><br></p><p>Yes thanks for 149.95</p><p><br></p><p>Now you can make the most delicious sandwiches, kebab mix and much more at home</p>")
}
}
Here height will increase automatically based on the size of content as well as width also.
More detail is available on this GitHub link: https://github.com/tmusabe/HTMLFormattedText-SwiftUI