我正在开发一个简单的 RSS 阅读器应用程序作为 Xcode 中的初学者项目。我目前已将其设置为解析提要,放置标题、发布日期、描述和内容,并将其显示在 WebView 中。
我最近决定在用于选择帖子的 TableView 中显示描述(或内容的截断版本)。但是,这样做时:
cell.textLabel?.text = item.title?.uppercaseString
cell.detailTextLabel?.text = item.itemDescription //.itemDescription is a String
它显示帖子的原始 HTML。
我想知道如何将 TableView 的详细 UILabel 的 HTML 转换为纯文本。
谢谢!
最佳答案
您可以添加此扩展以将您的 html 代码转换为常规字符串:
编辑/更新:
Discussion The HTML importer should not be called from a background thread (that is, the options dictionary includes documentType with a value of html). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.
Xcode 11.4 • Swift 5.2
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 { html2AttributedString?.string ?? "" }
}
extension StringProtocol {
var html2AttributedString: NSAttributedString? {
Data(utf8).html2AttributedString
}
var html2String: String {
html2AttributedString?.string ?? ""
}
}
cell.detailTextLabel?.text = item.itemDescription.html2String
关于ios - 在 Swift 中将 HTML 转换为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28124119/