当我滚动表格 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/