【问题标题】:Set UITableViewCell label to be generated from HTML string设置从 HTML 字符串生成的 UITableViewCell 标签
【发布时间】:2015-02-19 17:38:13
【问题描述】:

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

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

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

我该怎么做?

【问题讨论】:

    标签: ios uitableview swift tableview tableviewcell


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!它有效,我只需要它用于测试应用程序,因为我没有原始应用程序代码,所以滞后对我来说很好
    • 我可以对节标题做同样的事情吗?
    • 是的,你可以为任何标签做到这一点
    【解决方案2】:

    您可以使用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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 2012-07-12
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 2012-01-19
      相关资源
      最近更新 更多