【问题标题】:Reusable Cell isn't calling prepareForReuse functionReusable Cell 没有调用 prepareForReuse 函数
【发布时间】:2017-03-16 18:33:02
【问题描述】:

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

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


}

【问题讨论】:

  • 你不能这样覆盖prepareForReuse。您必须继承 UITableViewCell 并在子类声明中覆盖它。您需要将dequeueReusableCell(withIdentifier:for:) 的结果类型转换为您的子类。此外,从技术上讲,您应该首先将图像异步下载到磁盘,然后在用户滚动时将它们从磁盘加载到图像视图中。
  • 好的,你有一个例子说明它是如何工作的吗?

标签: ios swift xcode uitableview


【解决方案1】:

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

【讨论】:

  • 它在 UITableViewController 中,但我在同一个类中也有数据解析器。这会导致问题吗?此外,如果我将覆盖函数放在 tableview 函数之外,我会得到“方法不会覆盖其超类中的任何方法”和“使用未解析的标识符‘cell’”
  • 等一下。我认为我的问题是我将它全部塞进了控制器而不是 CELL ......让我快速检查一下。
  • @Garyb99 Exactly ;] 您需要在单元格内覆盖该方法,而不是在控制器中。
  • 谢谢。我现在成功地调用了这个函数。现在另一个问题。你如何从这里更改单元格属性?如果我输入“Cell.(在此处插入代码)”,那么它会给我“使用未解析的标识符单元”
  • @Garyb99 强烈建议您阅读 Apple 文档 developer.apple.com/reference/uikit/uitableviewcell,这是有关 API 的最佳信息来源。还可以查看这些指南:stackoverflow.com/documentation/ios/791/uitableview/6711/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2021-03-25
  • 2018-05-30
  • 2021-08-14
  • 2020-04-15
  • 2018-10-08
相关资源
最近更新 更多