【发布时间】:2017-08-02 16:01:02
【问题描述】:
我正在使用此代码在我的 customCell 中显示图像。 This 是我从 API 获取图像的代码。根据给定的链接,它工作正常。但是,当我将此代码添加到我的 cellForItemAt indexPath: 用于图像缓存时,问题就开始了。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Displaying other elements with text
customCell.mainImage.image = nil
var image1 = self.imageCache.object(forKey: indexPath.item as AnyObject) as? UIImage
if (image1 == nil) {
self.ImageFetcher(postId: self.myArray[indexPath.item].id!, completion: { (image) in
image1 = image
self.imageCache.setObject(image1!, forKey: indexPath.item as AnyObject)
})
}
DispatchQueue.main.async {
customCell.mainImage.image = image1
}
}
上面的代码可以正常工作,没有任何错误,但是在我上下滚动 collectionView 之前不会显示/加载图像。不明白我在这里缺少什么。任何帮助,将不胜感激 !!
【问题讨论】:
-
image1 = image=>DispatchQueue.main.async { customCell.mainImage.image = image } -
我尝试在
ImageFetcher中添加customCell.mainImage.image = image,但随后单元格显示错误图像,然后在快速滚动时再次更改为正确图像。 -
显示错误图片的原因是您在重复使用单元格时没有取消之前的图片加载。
-
我确实在我的 customCell 类中尝试了
override func prepareForReuse() { mainImage.image = nil super.prepareForReuse() },但没有区别! -
@Snehal 我认为你的 imageFetcher 功能不好
标签: xcode asynchronous swift3 grand-central-dispatch image-caching