【发布时间】:2020-04-07 05:46:18
【问题描述】:
我想将 NSAttributedString 转换为 HTML 字符串。我一直在寻找如何解决它,但我还没有结果。
知道我该怎么做吗?
【问题讨论】:
标签: html ios string swift nsattributedstring
我想将 NSAttributedString 转换为 HTML 字符串。我一直在寻找如何解决它,但我还没有结果。
知道我该怎么做吗?
【问题讨论】:
标签: html ios string swift nsattributedstring
let attrStr = NSAttributedString(string: "Hello World")
let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let htmlData = try attrStr.dataFromRange(NSMakeRange(0, attrStr.length), documentAttributes:documentAttributes)
if let htmlString = String(data:htmlData, encoding:NSUTF8StringEncoding) {
print(htmlString)
}
}
catch {
print("error creating HTML from Attributed String")
}
你可以使用这个代码。这是一个快速的例子
【讨论】:
可以包装在 NSAttributedString 的自己的扩展中
// swift 5.2
import Foundation
extension NSAttributedString {
func toHtml() -> String? {
let documentAttributes = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
do {
let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
return htmlString
}
}
catch {
print("error creating HTML from Attributed String")
}
return nil
}
}
【讨论】: