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

Jos*_*osh 5 uitableview ios swift

我正在尝试做一些非常基本的事情,但在其他类似问题中提出的修复似乎不起作用。我有一个图像缓存和一个 tableView。如果存在,我想显示缓存中的图像,否则应该什么都没有。出于某种原因,即使我将图像视图设置为 nil,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)
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我一生都无法弄清楚为什么图像没有被设置为零,即使我这样做是第一步!

Ole*_*ats 6

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

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

将您的单元格分配tagindexPath.row并测试单元格是否仍然与分配下载的图像相关:

/* right after cell dequeue */
cell.tag = indexPath.row
Run Code Online (Sandbox Code Playgroud)

然后

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

请注意:这仅适用于包含一个部分的 tableview。

PS 您可以将clean up您的单元格prepareForReuse放在 SearchResultsTableViewCell 内的方法中以稍微整理一下。


Jon*_*nah 0

您似乎将图像设置为,nil但您是否考虑过重复使用该单元时可能会进行的下载?当某些先前索引路径的下载完成时,您似乎可以更新单元格的图像。