【问题标题】:loading images into UICollectionView and caching issue将图像加载到 UICollectionView 和缓存问题
【发布时间】:2020-08-24 20:33:52
【问题描述】:

我已经用来自 API 的图像填充了 collectionView 并缓存了它。 它可以工作,但是最初加载图像时会出现问题。 imageView 在几分之一秒内占用了 collectionView 缓存中的一些其他图像,但它是可检测到的并且看起来很奇怪 相反,我想在加载之前将其保持为空。

AF.request(imageurlstring).responseImage { response in

            if case .success(let image) = response.result {
                self.image = image
                imageChache.setObject(image, forKey: NSString(string: urlString))
            }
        }

【问题讨论】:

  • 您是否尝试将 imageview 的图像设置为 nil 或集合视图单元格类的 prepareForReuse 方法中的占位符。
  • 是的@TonyNguyen,我试过了。它确实在一定程度上减少了问题,但有时仍然显示相同的问题

标签: ios swift caching uicollectionview


【解决方案1】:

发生这种情况是因为集合视图重用了单元格并且图像下载请求正在排队。这就是为什么对于某些单元格,您会获得这种多重图像设置。 为避免多重设置,您可以将图像的 url 保存在单元格内的某个位置。并检查它是否与响应的 url 匹配。

 cellImageURL = imageurlstring 
 AF.request(imageurlstring).responseImage { response in

       if case  .success(let image) = response.result
          if cellImageURL == response.request.url {
             self.image = image
          }
          imageChache.setObject(image, forKey: NSString(string: urlString))
       }
 }

【讨论】:

  • 它现在有自己的问题,除非我向下滚动然后向上滚动,否则单元格不会刷新。
【解决方案2】:

在设置任何新图像之前,请将图像设为 nil。所以在以下行之前添加 self.image = nil:
self.image = 图片

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多