简体   繁体   中英

loading images into UICollectionView and caching issue

I have filled the collectionView with images from an API and cached it. It works but there is a issue when images load initially. The imageView occupies some other image from the collectionView cache for a fraction of second but it is detectable and looks odd instead i would like to keep it empty until it loads.

AF.request(imageurlstring).responseImage { response in

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

在此处输入图像描述

This happens, because collection view reuses the cells and image download requests are being queued. That's why for some cells you get this multiple setting of images. To avoid the multiple setting you can save the url of the image somewhere inside the cell. And check if it match the url of a response.

 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))
       }
 }

Before setting any new image make the image as nil. So add self.image = nil before following line:
self.image = image

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