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

标签 ios swift swiftui

我正在尝试将 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/

相关文章:

Swift - 选择随机函数

uikit - 在 SwiftUI 中,如何将循环添加视频作为全屏背景图像?

ios - objectWillChange 不更新 View

swift - 不使用 CollectionView 的 ReusableCell 重用数据

iphone - 将 UIScrollView 手势识别器添加到另一个 UIScrollView

ios - 上传到 Firebase 时的图片方向问题

iphone - 单击时突出显示表格 View 单元格,而不是在释放时突出显示

没有 Storyboard或图像的 iOS 启动图像

ios - 将 Core Location 作为 ObservableObject 的 SwiftUI 崩溃

ios - 如何同时弹出模态视图和上一个导航 Controller View ?