gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:20:18 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com