在滚动之前,CollectionViewCell图像不会显示

时间:2017-08-02 16:01:02

标签: xcode asynchronous swift3 grand-central-dispatch image-caching

我正在使用此代码将图像显示在我的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之前,不显示/加载图像。别了解我在这里缺少的东西。任何帮助,将不胜感激 !!

2 个答案:

答案 0 :(得分:0)

请试试这个,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // Displaying other elements with text

    if let image1 = self.imageCache.object(forKey: indexPath.item as AnyObject) as? UIImage
    {
        customCell.mainImage.image = image1
    }
    else {
        self.ImageFetcher(postId: self.myArray[indexPath.item].id!, completion: { (image) in
            self.imageCache.setObject(image, forKey: indexPath.item as AnyObject)
            customCell.mainImage.image = image1
        })
    }
}

答案 1 :(得分:0)

  

步骤:1创建uiimageview的扩展名以从url下载图像,如果已经从缓存中下载了

   let imageCache = NSCache()
    extension UIImageView {

    func loadImageUsingCacheWithURLString(url: NSURL) {

        self.image = nil

        // First check if there is an image in the cache
        if let cachedImage = imageCache.objectForKey(url) as? UIImage {

            self.image = cachedImage

            return
        }

        else {
        // Otherwise download image using the url location in Google Firebase
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in

            if error != nil {
                print(error)
            }
            else {
                dispatch_async(dispatch_get_main_queue(), {

                    // Cache to image so it doesn't need to be reloaded every time the user scrolls and table cells are re-used.
                    if let downloadedImage = UIImage(data: data!) {

                        imageCache.setObject(downloadedImage, forKey: url)
                        self.image = downloadedImage

                    }
                })
            }
            }).resume()
        }

    }
  

第2步:使用

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // Displaying other elements with text
    customCell.mainImage.loadImageUsingCacheWithURLString(url: yoururl)
 }