试图在SwiftUI中表示的UIViewRepresentable中将HTML转换为AttributedString

问题描述 投票:3回答:1

我正在尝试使用UILabel创建此UIViewRepresentable视图,以便可以使用SwiftUI表示NSAttributedString。

我试图创建一个函数来转换此函数,但是它不起作用。

extension Data {
    var html2AttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            print("error:", error)
            return  nil
        }
    }
    var html2String: String {
        return html2AttributedString?.string ?? ""
    }
}

extension String {
    var html2AttributedString: NSAttributedString? {
        return Data(utf8).html2AttributedString
    }
    var html2String: String {
        return html2AttributedString?.string ?? ""
    }

    var noHTML: String {
        let str = self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
        return str
    }
}

这是当我有一个列表通过JSON给定的记录时得到的。

一旦我不使用html2AttributedString,一切都很好(显示HTML文本)。

似乎我无法使NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)部分正常工作。

=== AttributeGraph: cycle detected through attribute 38 ===  
=== AttributeGraph: cycle detected through attribute 38 ===  
=== AttributeGraph: cycle detected through attribute 41 ===  
=== AttributeGraph: cycle detected through attribute 19 ===  
=== AttributeGraph: cycle detected through attribute 33 ===  
=== AttributeGraph: cycle detected through attribute 38 ===  
=== AttributeGraph: cycle detected through attribute 19 ===
swift
1个回答
0
投票

我在使用Down库将markdown转换为属性字符串时遇到了相同的错误(实际上是将markdown转换为HTML归因字符串)。我必须显式地包装转换markdown的代码,并在DispatchQueue.main.async {}块中设置属性字符串以摆脱AttributeGraph错误。我不确定为什么首先会发生错误,但似乎与线程有关。

我不确定这是否对您的特定情况有所帮助,但是可能值得将代码的一部分包装到在DispatchQueue内的标签中设置属性字符串的位置。

© www.soinside.com 2019 - 2024. All rights reserved.