可重用单元不调用prepareForReuse函数

Ger*_*rit 3 xcode uitableview ios swift

好的,这里需要一些帮助.我是Swift的新手.这是我的问题.

在为我的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


}
Run Code Online (Sandbox Code Playgroud)

Ole*_*ats 7

您应该将UITableView单元格子类化为自定义类重写:

import UIKit

class CustomTableViewCell: UITableViewCell {

    override func prepareForReuse() {
        // your cleanup code
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在UITableViewDataSource方法中重用自定义单元格:

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