xcode 可重用单元不调用 prepareForReuse 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42842207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:50:30  来源:igfitidea点击:

Reusable Cell isn't calling prepareForReuse function

iosswiftxcodeuitableview

提问by Gerrit

Ok, need a little help here. I'm new to Swift. Here's my issue.

好的,这里需要一些帮助。我是斯威夫特的新手。这是我的问题。

When getting data for my UITableView, I'm calling image data from a url, so there is a slight delay when grabbing reused cells, resulting in the cell showing old data for half a second. I've tried to call func prepareForReuse to reset properties, but it doesn't seem to be working. Any help is appreciated!

在为我的 UITableView 获取数据时,我从 url 调用图像数据,因此在抓取重用的单元格时会有轻微的延迟,导致单元格显示旧数据半秒。我试图调用 func prepareForReuse 来重置属性,但它似乎不起作用。任何帮助表示赞赏!

Here's my code when calling cell:

这是我调用单元格时的代码:

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


}

回答by Oleh Zayats

You should subclass UITableView cell and inside your custom class override:

您应该子类化 UITableView 单元格并在您的自定义类覆盖中:

import UIKit

class CustomTableViewCell: UITableViewCell {

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

then in UITableViewDataSource method reuse the custom cell:

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

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