UITableView cell displays wrong image even when image is set to zero as first step in tableView.dequeueReusableCell
I'm trying to do something very basic, but the fix suggested in other similar questions doesn't seem to work. I have an image cache and a tableView. I want to display an image from the cache if it exists, otherwise there should be nothing. For some reason, the tableView still displays the reusable cell with the wrong image even when I set the image to zero. Below is my code:
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)
}
}
}
}
What am I doing wrong? I can't for the life of me figure out why the image isn't set to zero, even though I'm doing it as a first step!
source to share
The problem is with downloadImage.beginImageDownload
closures that contain uitableview cell references.
When you're done loading the images, you set the property cell.profilePhoto?.image
even if the tableView is recycling reusable cells to display a different row.
Assign cell tag
to indexPath.row
and check if the cell is still valid for the destination of the loaded image:
/* right after cell dequeue */
cell.tag = indexPath.row
then
/* download finished here */
if cell.tag == indexPath.row {
/* yeah, I want to rock this cell with my downloaded image! */
cell.profilePhoto?.image = downloadedImage
}
Be aware: this will only work in a single section tableview.
PS You can put clean up
your cells in a method prepareForReuse
inside SearchResultsTableViewCell to do a little work.
source to share