我正在尝试在 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 委托来按下它们。
但是,此代码运行非常缓慢,并且表格单元格不允许平滑滚动,而是在创建单元格后完全停止然后向下跳。
就像一个注释一样,我已经尝试注释掉属性的枚举以查看这是否是问题,但这根本不会加速单元格的创建。
如何改进此代码,谢谢!