Swift 3:在collectionView中caching图像

我目前正在通过我的应用程序,更新它与Swift 3一起工作,还有一个问题。 以前,我的图像caching工作得很好,但自更新以来, UIImageView在获取图像时没有被填充。

这里是代码(在...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以查明发生了什么事情。 当视图加载,我可以看到caching未命中,图像加载和UIImageView被填充的可见行,但是当我向下滚动, UIImageView s永远不会填充,日志显示CELL NOT FOUND: [0, x]为每个indexPath。

如果向下滚动后再次向上滚动,则按预期方式从caching中填充图像。

自从以前的Swift / iOS / Xcode版本以来,代码并没有改变,并且完美地工作。

我对任何第三方扩展等不感兴趣。 我想了解上面的代码有什么问题。 代码的任何其他改进/build议,但欢迎。

任何想法将非常感激!

而不是通过cellForItem(at: indexPath)方法获取单元格,只需使用您使用的cellvariables设置caching命中的图像。 这将创build一个强烈的参考单元格的图像视图。

 DispatchQueue.main.async(execute: { [weak collectionView] in cell.image.image = image collectionView?.reloadData() }) 

考虑将你的UIImageView重命名为imageView而不是image