【问题标题】:Is there any way to convert NSAttributedString to HTML in swift?有什么方法可以快速将 NSAttributedString 转换为 HTML?
【发布时间】:2020-04-07 05:46:18
【问题描述】:

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

知道我该怎么做吗?

【问题讨论】:

标签: html ios string swift nsattributedstring


【解决方案1】:
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")
}

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

【讨论】:

  • 如果我只想要带有 html 标签的文本,我该怎么做?你有什么想法吗
  • 我面临的最大问题是,当我使用这个时,内容的字体大小越来越大,为什么我不知道但它几乎翻了一番
  • 这不会返回简单的 html 字符串。
【解决方案2】:

可以包装在 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
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多