2017-03-16 10 views
2

ここで少し助けが必要です。私はスウィフトの新人です。ここに私の問題がある。再利用可能なセルがprepareForReuse関数を呼び出さない

私のUITableViewのデータを取得するとき、私はURLから画像データを呼び出しています。したがって、再利用されたセルを取得するときに若干の遅延があり、結果としてセルに半分の古いデータが表示されます。私はfunc prepareForReuseを呼び出してプロパティをリセットしようとしましたが、動作していないようです。どんな助けもありがとう!

セルを呼び出すときにここに私のコードです:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
    cell.alpha = 0 
    let book = books[indexPath.row] 
    cell.textLabel?.text = book.bookTitle 
    cell.detailTextLabel?.text = book.postURL 
    let url = URL(string: book.postPicture) 
    DispatchQueue.global().async { 
     let data = try? Data(contentsOf: url!) 
     DispatchQueue.main.async { 
      cell.alpha = 0 
      cell.backgroundView = UIImageView(image: UIImage(data: data!)) 
      UIView.animate(withDuration: 0.5, animations: { 
       cell.alpha = 1 
      }) 
     } 
    } 
    cell.contentView.backgroundColor = UIColor.clear 
    cell.textLabel?.backgroundColor = cell.contentView.backgroundColor; 
    cell.detailTextLabel?.backgroundColor = cell.contentView.backgroundColor; 

    func prepareForReuse(){ 
     cell.alpha = 0 
     cell.backgroundView = UIImageView(image: UIImage(named: "book.jpg")) 
    } 
    return cell 


} 
+0

あなたは 'prepareForReuse'をそのようにオーバーライドすることはできません。 'UITableViewCell'をサブクラス化し、それをサブクラス宣言でオーバーライドする必要があります。そして、 'dequeueReusableCell(withIdentifier:for:)'の結果をサブクラスに型キャストする必要があります。また、技術的には、まずディスクに画像を非同期にダウンロードしてから、ユーザーがスクロールしながらディスクから画像ビューに画像をロードする必要があります。 –

+0

これはどのように動作するかの例がありますか? – Gerrit

答えて

5

あなたはのUITableView細胞をサブクラス化し、カスタムクラスのオーバーライド内でなければならない:

import UIKit 

class CustomTableViewCell: UITableViewCell { 

    override func prepareForReuse() { 
     // your cleanup code 
    } 
} 

その後、UITableViewDataSourceメソッドでカスタムセルを再利用:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CustomTableViewCell 
    return cell 
} 
+0

これはUITableViewControllerにありますが、同じクラスにデータパーサーもあります。それは問題を引き起こす可能性がありますか?また、私は、tableview関数の外にオーバーライドfuncを置く場合、私は "メソッドは、スーパークラスからの任意のメソッドをオーバーライドしない"と "未解決の識別子 'セルの使用"を取得 – Gerrit

+0

ホールド。私は私の問題は、私がコントローラーでそれを詰め込み、セルではないということだと思います。 – Gerrit

+0

@ Garyb99 Exactly;]コントローラ内ではなく、セル内のメソッドをオーバーライドする必要があります。 –

関連する問題