Does NSHTMLTextDocumentType support HTML table?

2019-07-20 02:36发布

In my app, i want to display a text in a UILabel. I use HTML to store the text in my data base to dynamically from my text in my app. I actually use this (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

}

It's work great for the HTML stuff i used like

<b>Text</b>
<i>Test</i>
And more...

Now, i want to display a table in my label. This is the HTML code for the table :

<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>

This code displays a table form but there is no border in the table. I want to display the table border like the reel HTML render. It's possible or not ?

1条回答
闹够了就滚
2楼-- · 2019-07-20 03:33

Weird issue, I didn't understand why this simple thing didn't work, however I managed to make the border appear by adding a random attribute to the NSAttributedString, which makes me believe it's a NSAttributedString rendering bug.

Here's the function that I used (this is Swift 4 but can be converted to earlier versions):

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
    }
}
查看更多
登录 后发表回答