我正在开发一个简单的RSS阅读器应用程序,作为Xcode中的一个初学者项目。目前,我已经设置它来解析提要,并将标题、发布日期、描述和内容放在WebView中显示。
我最近决定在TableView中显示用于选择POST的描述(或内容的截断版本)。然而,在这样做时:
cell.textLabel?.text = item.title?.uppercaseString
cell.detailTextLabel?.text = item.itemDescription //.itemDescription is a String
它显示了文章的原始HTML。
我想知道如何将HTML转换成纯文本,只用于TableView的详细UILabel。
发布于 2018-08-03 13:27:34
可以添加此扩展以将html代码转换为常规字符串:
Xcode 9·SWIFT 4
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 ?? ""
}
}
Xcode 8.3·SWIFT 3.1
extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
cell.detailTextLabel?.text = item.itemDescription.html2String
发布于 2018-08-03 14:03:30
这是我建议的答案。如果你想把内部函数放在里面,而不是扩展。
func decodeString(encodedString:String) -> NSAttributedString?
{
let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
do {
return try NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
并调用该函数并将NSAttributedString转换为String。
let attributedString = self.decodeString(encodedString)
let message = attributedString.string
https://stackoverflow.com/questions/-100001904
复制相似问题