我的要求是在 SwiftUI
中显示包含 HTML
标签的文本。我尝试使用 WKWebKit::Loadhtml
的方法,效果很好。但是,我需要像这样显示它。
人物卡合集
人员卡:- 姓名职务
包含 HTML 文本的人员详细信息,例如Hello world
有人可以建议一种在 SwiftUI 中解决此问题的方法吗?
也引用了这篇文章,但没有运气
最佳答案
有多种方法可以在 SwiftUI 中显示 HTML 文本。但是我发现使用它们时存在一些问题。接口(interface)UILabel
和使用NSAttributedText
只能使我们能够显示小尺寸字符串,而且WKWebView
限制使用所需的字体。考虑到所有这些,我发现使用 UITextView
和 NSAttributedText
在 SwiftUI 中显示 HTML 文本更方便。代码如下
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>")
}
}
这里的高度会根据内容的大小以及宽度自动增加。 更多详细信息请访问此 GitHub 链接:https://github.com/tmusabe/HTMLFormattedText-SwiftUI
关于ios - 如何在 SwiftUI 中显示 HTML 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59726570/