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)
我究竟做错了什么?我一生都无法弄清楚为什么图像没有被设置为零,即使我这样做是第一步!
问题是downloadImage.beginImageDownload闭包持有对 uitableview 单元格的引用。
完成图片下载后,设置cell.profilePhoto?.image属性,即使 tableView 回收可重用单元格以显示不同的行。
将您的单元格分配tag给indexPath.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 内的方法中以稍微整理一下。
| 归档时间: |
|
| 查看次数: |
1294 次 |
| 最近记录: |