【问题标题】:How to fix in transform NSAttributedString from html string in swift?如何在swift中从html字符串转换NSAttributedString?
【发布时间】:2019-08-07 03:33:00
【问题描述】:

当我将 html 字符串转换为 NSAttributedString 时,它可以正常工作,但在特定情况下会出现问题。

func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
        do {
            let htmlCSSString = "<style>" +
                "html *" +
                "{" +
                "font-size: \(size)px;" +
                "color: \(color.hex);" +
                "font-family: \(family ?? "Helvetica"), Helvetica;" +
            "}</style> \(self)"

            guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                return nil
            }

            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            return nil
        }
    }

这是我的测试用例 html 字符串有问题。 &lt;b&gt;Hi &lt;i&gt;how are &lt;u&gt;you?&lt;/u&gt;&lt;/i&gt;&lt;/b&gt;

这是我使用 NSAttributedString 的结果。 你好吗?

我想在这句话中全部加粗,但我只得到Hi粗体字符串。

【问题讨论】:

    标签: html ios swift iphone nsattributedstring


    【解决方案1】:

    似乎有效。对于此快速测试,颜色已更改为 String 类型。您的函数包含在 String 扩展中。以下是对该函数的调用。返回的属性字符串被转换为 MS Word 格式的数据,得到上面的最后一句话,在 Word 中显示。

    var s = "<b>Hi <i>how are <u>you?</u></i></b>"
    var attr = s.htmlAttributed(family: nil, size: 20, color: "blue")
    
    var MWdata = attr!.docFormat(from: NSRange(location: 0, length: attr!.length),documentAttributes: [NSAttributedString.DocumentAttributeKey(rawValue: "documentType"):NSAttributedString.DocumentType.docFormat])                  
    

    【讨论】:

    • NSAttributedString.DocumentAttributeKey(rawValue: "documenType") ???它缺少一个“t”,为什么不使用密钥?
    • 修复了缺失的“t”。由于 MWdata 行与关于代码的初始问题无关,因此我没有花时间弄清楚如何使用 docFormat() 方法。我只是在 Xcode 编辑器的帮助下使用这种不熟悉的方法即时输入文本。
    • 问题是为什么要NSAttributedString.DocumentAttributeKey(rawValue: "documentType") 而你应该做NSAttributedString.DocumentAttributeKey.documentType?如果 Apple 在下一个版本中更改 rawValue 怎么办?
    猜你喜欢
    • 1970-01-01
    • 2016-02-23
    • 2018-08-12
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多