NSHTMLTextDocumentType是否支持HTML表格?

3

我希望在我的应用中,能够在UILabel上显示一段文本。我使用HTML将该文本存储在我的数据库中,以便在我的应用程序中动态地从文本获取内容。目前我正在使用以下代码 (Swift 3.2, iOS 8+):

if let data = text.data(using: .utf8) {
    let htmlString = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)

    self.textLabel.attributedText = htmlString

}

它非常适用于我使用的HTML相关工作,比如:
<b>Text</b>
<i>Test</i>
And more...

现在,我想在我的标签中显示一个表格。这是表格的HTML代码:
<table border="2px solid black">
<tr><th>Symbole</th><th>Å</th><th>↓</th><th>■</th><th>╩</th><th>¬</th><th>▓</th><th>Ø</th><th>±</th><th> º </th><th>¶</th><th>░</th></tr>
<tr><td>Utilisation</td><td>1</td><td>11</td><td>11</td><td>5</td><td>1</td><td>4</td><td>12</td><td>4</td><td>1</td><td>5</td><td>1</td></tr>
</table>

这段代码显示了一个表单,但是表格中没有边框。我想要像真正的 HTML 渲染一样显示表格边框。这是可能的吗?
1个回答

7

有一个奇怪的问题,我不理解为什么这个简单的东西不起作用,但是我添加了一个随机属性到NSAttributedString中,边框就出现了。这让我相信这是NSAttributedString的渲染错误导致的。

这是我使用的函数(这是Swift 4,但可以转换为更早的版本):

extension String {
    func attributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf8,
            allowLossyConversion: false) else { return nil }
        let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            NSAttributedString.DocumentReadingOptionKey.characterEncoding : String.Encoding.utf8.rawValue,
            NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html
        ]
        let htmlString = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil)

        // Removing this line makes the bug reappear
       htmlString?.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.clear, range: NSMakeRange(0, 1))

        return htmlString
    }
}

感谢您提供的临时解决方案。在我的情况下有效。 - Jordan Favray
临时修复是iOS开发的一种常见做法。 - Haroun Hajem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接