有什么方法可以快速将 NSAttributedString 转换为 HTML 吗?

Cha*_*ima 7 html string nsattributedstring ios swift

我想将 NSAttributedString 转换为 HTML 字符串。我一直在寻找如何解决它,但还没有结果。

知道我该怎么做吗?

小智 3

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")
}
Run Code Online (Sandbox Code Playgroud)

你可以使用这个代码。它是一个快速的例子

  • 如果我只想要带有 html 标签的文本,我该怎么做?你有什么想法吗 (2认同)