I am attempting to display, correctly formatted HTML text in a UILabel and have succeeded with the following code:
// 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
The code also correctly finds and locates the links in the text and allows the user to press on them by using the TTTAtributedLabel delegate.
This code however runs very slowly and the table cells do not allow for smooth scrolling, instead it stops completely then jumps down after the cells have been created.
Just as a note, I have tried commenting out the enumerating of the attributes to see if this is the problem but this does not speed up the cells creation at all.
How can I improve this code, thanks!