我目前正在开发我的应用程序,将其更新为与 Swift 3 兼容,但还剩下一个问题。以前,我的图像缓存工作得很好,但自从更新后UIImageView
获取图像时不会填充 s。
这是代码(在...cellForItemAt...
功能):
if let img = imageCache[imageUrl] {
print("CACHE HIT: \(indexPath)")
cell.image.image = img
} else {
print("CACHE MISS: \(indexPath)")
var imgUrl: = URL(string: imageUrl)
let request: URLRequest = URLRequest(url: imgUrl!)
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
if(data != nil) {
print("IMAGE DOWNLOADED: \(imgUrl?.query))")
let image = UIImage(data: data!) // create the image from the data
self.imageCache[imageUrl] = image // Store in the cache
DispatchQueue.main.async(execute: {
if let cell = collectionView.cellForItem(at: indexPath) as? MyCollectionViewCell {
print("APPLYING IMAGE TO CELL: \(indexPath)")
cell.image.image = image
self.collectionView.reloadData()
} else {
print("CELL NOT FOUND: \(indexPath)")
}
})
}
})
dataTask.resume()
}
正如你所看到的,我添加了一些print
来了解发生了什么事。当视图加载时,我可以看到缓存未命中,以及图像加载和UIImageView
s 被填充为可见行,但是当我向下滚动时,UIImageView
s 从未被填充,日志显示CELL NOT FOUND: [0, x]
对于每个索引路径。
如果我在向下滚动后再次向上滚动,图像将从缓存中按预期填充。
自 Swift / iOS / Xcode 的上一个版本以来,代码没有改变,并且曾经完美地工作。
我对任何第三方扩展等不感兴趣;我想了解上面的代码有什么问题。不过,欢迎对代码进行任何其他改进/建议。
任何想法将不胜感激!
而不是通过获取细胞cellForItem(at: indexPath)
方法,只需使用cell
用于设置缓存命中中的图像的变量。这将为单元格的图像视图创建一个强引用。
DispatchQueue.main.async(execute: { [weak collectionView] in
cell.image.image = image
collectionView?.reloadData()
})
考虑重命名您的UIImageView
to imageView
而不是image
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)