NSHTMLTextDocumentType是否支持HTML表?

时间:2017-10-03 14:27:41

标签: html ios swift html-table uilabel

在我的应用中,我想在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 个答案:

答案 0 :(得分:4)

奇怪的问题,我不明白为什么这个简单的东西不起作用,但是我设法通过在NSAttributedString中添加一个随机属性来显示边框,这让我相信它#sa; sa 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
    }
}