简体   繁体   中英

UICollectionView load image cannot get correct cell swift 3

My UICollectionView is fetching images in cellForItemAt . After I upgrade to swift 3, some images are not showing when I scroll very fast. Here is my code in cellForItemAt :

if (imageNotInCache) {
    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
    if let thumb = imageFromPathAndCacheIt(path) {
      DispatchQueue.main.async {
          let updateCell = collectionView.cellForItem(at: indexPath) as! MyCustomCell? {
             updateCell.imageView.image = thumb
          }
   }
}

The problem is, sometimes I get updateCell as nil even it is on the screen (probably because scroll to fast).

I know we can add reloadData after adding the image, just like: Swift 3: Caching images in a collectionView , but I don't want to call reload so many times.

Thank you for interested in this question. Any ideas would be very appreciated!

There's definitely a compromise between accessing and manually updating the cell view content, and calling reloadData on the whole collection view that you could try.

You can use the func reloadItems(at: [IndexPath]) to ask the UICollectionView to reload a single cell if it's on screen.

Presumably, imageNotInCache means you're storing image in an in-memory cache, so as long as image is also accessible by the func collectionView(UICollectionView, cellForItemAt: IndexPath) , the following should "just work":

if (imageNotInCache) {
    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
        if let thumb = imageFromPathAndCacheIt(path) {
            DispatchQueue.main.async {
                self.collectionView.reloadItems(at: [indexPath])
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM