【发布时间】:2020-08-17 21:31:36
【问题描述】:
Html 标签来自 api 响应的字符串,需要显示格式化字符串而不是标签。以下是我尝试过的代码:
html 字符串:
"<span class="st"><em>Bread<\/em> is a staple food, usually by baking. Throughout ... <em>Sourdough<\/em> is a type of <em>bread<\/em> produced by dough using naturally occurring yeasts and lactobacilli. ... List of <em>toast<\/em> dishes<\/span>",
代码尝试:
let data = Data(vm.description!.utf8)
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
infoDescription.attributedText = attributedString
}
尝试了其他方法:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
请指导我做错了什么或缺少什么。谢谢
【问题讨论】:
-
这能回答你的问题吗? How to decode html formatted text in Swift 3
标签: html ios swift nsattributedstring