【问题标题】:NSAttributedString to HTML in iOS Swift 3NSAttributedString 到 iOS Swift 3 中的 HTML
【发布时间】:2017-12-08 23:58:37
【问题描述】:

我搜索了很多,但只能找到纯文本的 HTML,而不是反过来,我的应用程序中有电子邮件实现,因此需要将电子邮件的内容作为 HTML 发送到后端。

编辑 1:我有包含粗体、斜体、有序/无序列表、带下划线的单词的富文本。

【问题讨论】:

  • 你指的是什么 HTML 东西,我是否必须创建一个函数或其他东西来将其转换为 HTML 格式。
  • <html><body>YOUR CONTENT HERE</body></html> 现在你的文本显示在 xml / html 中。
  • @luk2302 实际上我有一个富文本,即粗体、斜体、有序/无序列表等。我想我也应该在我的问题中提到这一点
  • ... 这基本上与纯文本相反。所以你在问如何将格式化文本转换成看起来与格式化文本相同的 html。
  • @user832 您是否正在寻找将NSAttributedString 转换为html 文本的方法?

标签: html ios swift


【解决方案1】:

根据this post:

private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch { }
    return nil
}

【讨论】:

  • 这与 OP 的要求相反。
【解决方案2】:

如果您希望将NSAttributedString 转换为String,这是您正在寻找的扩展方法。只需拨打yourAttributtedString.htmlString() 并打印出来。

extension NSAttributedString {
    func htmlString() -> String? {
        let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        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 {}
        return nil
    }
}

【讨论】:

  • 我需要将 NSAttributedString 转换为 HTML
  • @user832 swift 中没有 HTML 元素。我正在将NSAttributedString 转换为一个快速的String 对象,它是html 字符串。当您使用此字符串发送电子邮件时,您会看到它以 html 格式显示为您的格式化内容
  • 它没有检测粗体、斜体等格式,只是转换为带有段落属性的 HTML
  • @user832 那是因为你还没有添加任何字体。尝试为您的 NSAttrbuttedDtring 设置一些粗体,然后重试
猜你喜欢
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多