我正在尝试将 HTML
格式的文本转换为属性字符串,并将其插入到 SwiftUI
View 中。
首先,我有一个 String
扩展,可以将 HTML
字符串转换为 NSAttributedString
:
extension String {
func convertHtml() -> NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return attributedString
} else {
return NSAttributedString()
}
}
}
然后我创建了一个 HTMLLabel
View :
struct HTMLLabel: UIViewRepresentable {
let html: String
func makeUIView(context: UIViewRepresentableContext<Self>) -> UILabel {
let label = UILabel()
label.attributedText = html.convertHtml()
return label
}
func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<Self>) {}
}
然后我将一个测试插入到我的 SwiftUI View 中:
HTMLLabel(html: "<html><body><b>Hello</b> <i>World</i></body></html>")
代码每次在 if let attributedString = try? ...
与 EXC_BAD_INSTRUCTION
。我在这样一个空的 Storyboard项目中进行了测试:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 50, y: 50, width: 320, height: 50))
label.attributedText = "<html><body><b>Hello</b> <i>World</i></body></html>".convertHtml()
view.addSubview(label)
}
}
该代码执行时没有任何问题。为什么代码在 SwiftUI
上下文中不起作用?
最佳答案
使用这个:-
struct HTMLLabel: UIViewRepresentable {
let html: String
func makeUIView(context: UIViewRepresentableContext<Self>) -> UILabel {
let label = UILabel()
DispatchQueue.main.async {
if let attributedText = self.html.convertHtml() {
label.attributedText = attributedText
}
}
return label
}
func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<Self>) {}
}
NSAttributedString.DocumentType.html 仅适用于主线程这就是您崩溃的原因
关于ios - 来自 HTML 的 SwiftUI 属性字符串使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59731236/