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 に答える