4

我正在尝试在 UILabel 中显示格式正确的 HTML 文本,并成功使用以下代码:

    // Create the html body
    var attributedHTMLBody = NSAttributedString(data: comment.bodyHTML.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: false), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil, error: nil)

    // Create the string including the text style
    var htmlString = String(format: "<div style='font-size: 16px; font-family: HelveticaNeue-Light;'>%@", attributedHTMLBody.string)

    // Create the final text to display
    var attributedHML = NSAttributedString(data: htmlString.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: false), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil, error: nil)

    // Set the text
    cell.commentLabel.attributedText = attributedHML

    // Find the locations of any links
    var mutableLinkArray = NSMutableArray()
    var mutableRangeArray = NSMutableArray()
    attributedHML.enumerateAttributesInRange(NSMakeRange(0, attributedHML.length), options: NSAttributedStringEnumerationOptions.LongestEffectiveRangeNotRequired, usingBlock: {attribute, range, stop in

        // Get the attributes
        var attributeDictionary = NSDictionary(dictionary: attribute)

        if let link = attributeDictionary.objectForKey("NSLink") as? NSURL {
            mutableLinkArray.addObject(link)
            mutableRangeArray.addObject(range)
        }

    })

    // Add links to the label
    for var i = 0; i < mutableLinkArray.count; i++ {
        cell.commentLabel.addLinkToURL(mutableLinkArray[i] as NSURL, withRange: mutableRangeArray[i] as NSRange)
    }

    // Set the labels delegate
    cell.commentLabel.delegate = self

该代码还正确地找到并定位了文本中的链接,并允许用户通过使用 TTTAtributedLabel 委托来按下它们。

但是,此代码运行非常缓慢,并且表格单元格不允许平滑滚动,而是在创建单元格后完全停止然后向下跳。

就像一个注释一样,我已经尝试注释掉属性的枚举以查看这是否是问题,但这根本不会加速单元格的创建。

如何改进此代码,谢谢!

4

1 回答 1

6

使用UITextView.

使用 iOS8,实现动态单元格高度非常简单。使用文本视图设置单元格,并围绕文本视图和单元格上的其他视图设置约束。确保在界面生成器中将内容压缩阻力和内容拥抱优先级设置为 100%。您可以在代码中实现所有这些,但在界面构建器中要简单得多。

现在在代码中,当您的控制器加载时,将估计的单元格高度设置为您认为有些准确的估计值。表格视图将根据内容显示具有正确高度的单元格。

于 2014-10-08T16:57:08.107 回答