将 UITableViewCell 标签设置为从 HTML 字符串生成

Set UITableViewCell label to be generated from HTML string

我在 swift 上使用 TableView,我想知道如何设置从 HTML 字符串生成的 UITableViewCell 标签。

我知道如何使用它在单元格标签上显示文本:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    var articlesInSection = xmlParser.channelsArray[indexPath.section]["articles"] as [AnyObject]

    //articleWebView.loadHTMLString(activeItem, baseURL: nil)

    cell.textLabel?.text = articlesInSection[indexPath.row]["title"] as NSString

    return cell
}

但我有一个 HTML 我想显示而不是文本,类似于 loadHTMLString function

我该怎么做?

您可以使用 NSAttributedString 来显示来自 html 的文本,但我认为这不是 table 视图单元格中非常有效的解决方案,因为它会在滚动时导致延迟 and/or 延迟正在加载

var attrStr = NSAttributedString(
            data:yourHTMLString.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil,
            error: nil)
cell.textLabel?.attributedText = attrStr

您可以使用AttributedString
Swift 5

中的示例
do {
   let attrStr = try NSAttributedString(data: htmlStr.data(using: .unicode, allowLossyConversion: true)!, options: [.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
   cell.textLabel?.attributedText = attrStr
} catch {
   print(error)
}