ios - Reusable Cell 没有调用 prepareForReuse 函数

标签 ios swift xcode uitableview

好的,这里需要一点帮助。我是 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


}

最佳答案

您应该继承 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
}

关于ios - Reusable Cell 没有调用 prepareForReuse 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42842207/

相关文章:

ios - UIScrollView 和约束问题

iOS 背景图像在 iPad 中重复出现?

ios - Swift:ImageView 方面填充错误

ios - 我不知道为什么结果不是我想的

swift - 使用什么控件从相机捕获图像并在 ui 上显示为带有事件的缩略图 xamarin ios

xcode - dyld:库未加载:/System/Library/Frameworks/Social.framework/Social

ios - 在 Xcode 中创建带有 slider 的倒计时表

ios - 遇到405错误如何删除collectionview记录?

ios - 谁能告诉我为什么 addObject 给出不稳定的结果?

使用 MVVM 模式显示数组中的值的 SwiftUI 问题