我正在使用 Firebase
将图像加载到单元格的 ImageView
中,但是!有一个问题。我正在使用缓存机制来防止在可重用单元格
加载时重新下载图像,但在滚动TableView
之前图像不会加载。
这是代码;
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.imgv.image = nil
if let urlString = self.filteredFlats[indexPath.row].flatThumbnailImage?.imageDownloadURL
{
imageURLString = urlString
let url = URL(string: urlString)
if let imagefromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage
{
DispatchQueue.main.async {
cell.imgv.image = imagefromCache
return
}
}
else
{
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
DispatchQueue.main.async {
let imagetoCache = UIImage(data:data!)
if self.imageURLString == urlString
{
cell.imgv.image = imagetoCache
}
self.imageCache.setObject(imagetoCache!, forKey: urlString as AnyObject)
}
}).resume()
}
}
return cell
}
我认为问题是,当 URLSession
下载图像并将其设置到 ImageView
中时,但加载的图像直到 indexpath.row 才显示
上下滚动时回调。
我意识到原因是这个if语句;
if self.imageURLString == urlString
但是如果我删除它,由于可重复使用的细胞的行为,细胞会变得更糟。一些单元格仍然显示旧的缓存图像。
真的不知道发生了什么。没想到 TableViews 是一种复杂的结构。
谢谢。
最佳答案
我猜测 imageURLString 是你的类的一个字段(可能是 UIViewController )。
这意味着每次您进入方法时 imageURLString = urlString
都会更改其值。
渲染表格时,它将调用每个单元格的方法,如果所需的图像不在缓存中,则每次都会触发下载。但在这些调用之后,imageURLString
的值将是最后一个单元格使用的 url,因此只有这个单元格才会真正使用已加载的图像。
如果您想修复代码,每个单元格应该有一个 imageURLString
,例如通过将字段移动到单元格类(在此创建一个 UITableViewCell
子类)情况),并将 imageURLString
和 self.imageURLString
替换为 cell.imageURLString
关于ios - TableView 图像在滚动之前不会加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41224294/