Does NSHTMLTextDocumentType support HTML table?

亡梦爱人 提交于 2019-12-23 17:12:08

问题


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:


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


来源:https://stackoverflow.com/questions/46546994/does-nshtmltextdocumenttype-support-html-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!