My requirement is to display the text in SwiftUI
which contains the HTML
tags. I tried with the approach of using the WKWebKit::Loadhtml
which works fine . However, I have the requirement of displaying it something like this. A collection of person card
Person card:- Name Title
Person details details which has HTML text e.gHello world
Can someone suggest a way to solve this in SwiftUI
.
Refer to the post as well but no luck
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.