背景:当我从 Web 服务检索字符串时,它包含 HTML 标记。我得到的是:
"Most children who have chronic ear infections outgrow them over time.<div><br></div><div><br></div><div>test</div><div><br></div><div><br></div><div><br></div><div>test1</div>").
现在,我通过将其转换为 attributeString 将其显示到 UITextView,这样用户就不会看到所有 HTML 标签。我将此字符串转换为 attributeString,如下所示,带有两个扩展名:
extension: String {
var data: Data {
return Data(utf8)
}
extension Data {
var attributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print(error)
}
return nil
}
self.textView.attributedText = htmlTagString.data.attributedString
现在,用户将能够在没有 HTML 标签的情况下查看 TextView 的属性文本。但是当他们保存它时,我只保存了 textView.attributedText.string 但通过这样做,字符串的 HTML 标签都消失了,但我还需要保存它们,例如
等。
问题:如何保留 TextView 的字符串/文本的 HTML 标签?请并谢谢您。
最佳答案
swift 4:
extension NSAttributedString {
var attributedStringToHtml: String? {
do {
let htmlData = try self.data(from:NSMakeRange(0, self.length), documentAttributes:[.documentType: NSAttributedString.DocumentType.html]);
return String.init(data: htmlData, encoding: String.Encoding.utf8)
} catch {
print("error:", error)
return nil
}
}
}
以前的 swift 版本:
extension NSAttributedString {
var attributedStringToHtml: String? {
do {
let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType])
return String(data:htmlData, encoding:String.Encoding.utf8)
} catch {
print("error:", error)
return nil
}
}
}
关于html - 如何将 HTML 标签添加到 UITextView Swift Xcode 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53234709/