HTML的SwiftUI属性字符串使应用程序崩溃 [英] SwiftUI attributed string from HTML crashes the app
问题描述
我正在尝试将HTML
格式的文本转换为属性字符串,并将其插入到SwiftUI
视图中.
I'm trying to convert HTML
formatted text into an attributed string, and insert it into a SwiftUI
view.
首先,我有一个String
扩展名,它将HTML
字符串转换为NSAttributedString
:
Firstly I have a String
extension that converts the HTML
string to 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
视图:
Then I have created a 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视图中
Then I insert a test into my SwiftUI view:
HTMLLabel(html: "<html><body><b>Hello</b> <i>World</i></body></html>")
每次在if let attributedString = try? ...
和EXC_BAD_INSTRUCTION
上代码崩溃.我在一个空的故事板项目中进行了如下测试:
The code crashes each time on if let attributedString = try? ...
with EXC_BAD_INSTRUCTION
. I made a test in an empty storyboard project like this:
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
上下文中工作?
That code executes without any issues. Why doesn't the code work in a SwiftUI
context?
推荐答案
使用此功能:-
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仅与主线程一起使用,这就是您崩溃的原因
NSAttributedString.DocumentType.html is Only Work with Main Thread That's why you are getting crash
这篇关于HTML的SwiftUI属性字符串使应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!