来自 HTML 的 SwiftUI 属性字符串使应用程序崩溃

Chr*_*ris 7 ios swift swiftui

我正在尝试将HTML格式化文本转换为属性字符串,并将其插入到SwiftUI视图中。

首先,我有一个StringHTML字符串转换为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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个HTMLLabel视图:

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>) {}

}
Run Code Online (Sandbox Code Playgroud)

然后我在我的 SwiftUI 视图中插入一个测试:

HTMLLabel(html: "<html><body><b>Hello</b> <i>World</i></body></html>")
Run Code Online (Sandbox Code Playgroud)

每次打开if let attributedString = try? ...时代码都会崩溃EXC_BAD_INSTRUCTION。我在一个空的故事板项目中做了一个测试,如下所示:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

该代码执行没有任何问题。为什么代码在SwiftUI上下文中不起作用?

Pus*_*dra 10

用这个:-

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>) {}

}
Run Code Online (Sandbox Code Playgroud)

NSAttributedString.DocumentType.html 仅适用于主线程这就是您崩溃的原因