UITableView单元格显示不正确的图像,即使将图像设置为零作为tableView.dequeueReusableCell中的第一步

我正在尝试做一些非常基本的事情,但是在其他类似问题中提出的修复似乎并不奏效。 我有一个图像caching和一个tableView。 如果存在,我想要显示caching中的图像,否则应该没有任何内容。 出于某种原因,即使将图像视图设置为零,tableView仍然会显示错误图像的重用单元格。 以下是我的代码:

let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath) as! SearchResultsTableViewCell cell.profilePhoto?.image = nil cell.profilePhoto?.backgroundColor = UIColor.gray if let userID = myObject.posterId, let profileImage = self.imageCache.object(forKey: userID as AnyObject) { cell.profilePhoto?.image = profileImage } else { if let userId = myObject.posterId { downloadImage.beginImageDownload() { (imageOptional) in if let image = imageOptional { cell.profilePhoto?.image = image self.imageCache.setObject(image, forKey: userId as AnyObject) } } } } 

我究竟做错了什么? 我不能为了我的生活找出为什么图像没有设置为零,即使我这样做的第一步!

问题是downloadImage.beginImageDownload闭包持有对uitableview单元格的引用。

当您完成图像下载时,即使tableView回收可重复使用的单元格以显示不同的行,也可以设置cell.profilePhoto?.image属性。

将单元格的tag分配给indexPath.row并testing单元格是否与指定下载的图像相关:

 /* right after cell dequeue */ cell.tag = indexPath.row 

然后

 /* download finished here */ if cell.tag == indexPath.row { /* yeah, I want to rock this cell with my downloaded image! */ cell.profilePhoto?.image = downloadedImage } 

请注意:这只会在一个部分的tableview中工作。

PS你可以把你的单元格clean upprepareForReuse里面的prepareForReuse方法中来整理一些东西。

您似乎将图像设置nil但是您是否考虑过重复使用该单元格时可能nil的下载? 它看起来像你可能会更新一个单元格的图像时,一些先前的索引path下载完成。