swift - UITableViewCell 滚动时继续更改其图像

标签 swift uitableview

当我滚动表格 View 时,tableViewCell 的图像不断更改错误的图像。

我尝试过这个。

@IBOutlet weak var imageView: UIImageView!

override prepareForReuse() {
    super.prepareForReuse()

    self.imageView.image = nil
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? MyCustomCell else { return UITableViewCell() }
    cell.tag = indexPath.row
    if cell.tag == indexPath.row {
        // download image
        downloadManager.download { (image) in
            cell.imageView.image = image
        }
    }
}

但是,滚动时图像仍然不正确。 我该如何解决它??

最佳答案

下载图像(异步)后,您需要检查您的单元格是否确实与该图像相关。

例如。单元格可能会被另一个索引路径重复使用,因此下载的图像不再正确。

我添加了 index (indexPath.row) 来下载完成闭包,以便您可以检查 cell.tag 是否等于索引

downloadManager.download(index: indexPath.row) { (image, index) in
    if cell.tag == index {
    cell.imageView.image = image
    }
}

关于swift - UITableViewCell 滚动时继续更改其图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605627/

相关文章:

Swift 图像语法

swift - 如何修复 `Value of type ' [ReceiptInfo ]' (aka ...) has no member ' compactMap'`?

ios - 监控 UITableViewCell 在屏幕上显示多长时间

objective-c - 如何避免我的 UITextView 被我的 UITableView 覆盖?

ios - 删除UITableViewCell并与Plist同步

ios - 如何在TableController的ImageView中正确添加图片?

swift - 需要知道在外部类中定义的内部类的变量名

ios - Swift 类型推断需要问号或感叹号

ios - 在静态 TableView (单元格)中实现动态表

ios - 如何在 UITableView 中添加背景视频并使其在滚动 UITableViewCells 时固定?