html - 在 Swift 4 中将属性文本转换为 HTML

标签 html ios swift nsattributedstring

我正在尝试在 Swift 4 中将属性文本转换为 HTML,以便它可以存储在 Firebase/Firestore 中并在不同的设备/平台之间同步。我已经阅读了在 Stackoverflow 上可以找到的所有文章,包括 Convert attributed string, to, "simple" tagged html , Convert attributed text to HTML和这篇博客文章:http://sketchytech.blogspot.com/2016/02/swift-from-html-to-nsattributedtext-and.html .我发现 Swift 4.x 在各种代码示例(下面的示例)中为 NSDocumentTypeDocumentAttribute 和 NSHTMLTextDocumentType 抛出了一个 Unresolved 标识符错误。这些错误不会在 Swift 3.x 中抛出。 Xcode 建议我可能打算使用 NSDocumentTypeDocumentOption 但不提供修复,我不确定这是否是我想要的或者如果是的话如何使用它。

let myAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.green ]
let attrString = NSAttributedString(string: "Hello.", attributes: myAttributes)
let x = attrString
var resultHtmlText = ""
do {

    let r = NSRange(location: 0, length: x.length)
    let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

    let d = try x.data(from: r, documentAttributes: att)

    if let h = String(data: d, encoding: .utf8) {
        resultHtmlText = h
    }
}
catch {
    print("utterly failed to convert to html!!! \n>\(x)<\n")
}
print(resultHtmlText)

谢谢你的帮助

最佳答案

对于 Swift 4.x,行:

let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

应该是:

let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]

关于html - 在 Swift 4 中将属性文本转换为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50126120/

相关文章:

ios - 从 UIViewController 将数据传递到 UIView 未按预期工作

html - 在视频上叠加文字

css - 禁用 div 内容错误

android - 如果添加了启动画面,则状态栏不会在Flutter中的其他画面上显示

iOS 证书导入 - .p12 与 NSData

ios - 加载保存到文档目录的图像只能工作一次,然后再也不会加载

Javascript 未正确将变量传递给 Modal

html - 换行时文本的字体大小增加

ios - 视频 iOS 7 上的模糊 Pane

ios - Swift,靠近用户位置