我试图在 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 委托(delegate)点击它们。
然而,此代码运行速度非常慢,并且表格单元格不允许平滑滚动,而是完全停止,然后在创建单元格后向下跳转。
请注意,我尝试注释掉属性的枚举以查看这是否是问题所在,但这根本不会加速单元格的创建。
我该如何改进这段代码,谢谢!
最佳答案
使用 UITextView
。
在 iOS8 中,实现动态单元格高度非常简单。使用 TextView 设置单元格,并围绕 TextView 和单元格上的其他 View 设置约束。确保在界面生成器中将内容压缩阻力和内容拥抱优先级设置为 100%。您可以在代码中实现所有这些,但在界面构建器中要简单得多。
现在在代码中,当您的 Controller 加载时,将估计的 单元格高度设置为您认为比较准确的估计值。表格 View 将根据内容显示具有正确高度的单元格。
关于ios - 在 UILabel 中显示 HTML 文本,性能问题。 [iPhone SDK、iOS 8、Swift],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26254828/