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 デリゲートを使用してリンクを押すことができるようにします。
ただし、このコードの実行は非常に遅く、表のセルはスムーズにスクロールできません。代わりに、セルが作成された後に完全に停止し、下にジャンプします。
注意として、属性の列挙をコメントアウトして、これが問題であるかどうかを確認しましたが、これによってセルの作成がまったく高速化されることはありません。
どうすればこのコードを改善できますか、ありがとう!