如何防止在cellForItemAt中重新加载UICollectionViewCell?

时间:2017-12-08 22:00:55

标签: ios swift uicollectionview uicollectionviewcell

我有一个CollectionViewController,我在其中联系API以根据一组坐标下载图像。我在cellForItemAt函数中调用此代码,此时它使用来自Flickr的图像实时更新单元格的图像。这很好。

然而,当向上或向下滚动时,它会调用此代码并再次更新单元格,当我更喜欢查看现有单元格时,确定它们是否已填充,并且根本不运行此代码。

我已经尝试在网络代码之前实现逻辑,该代码检查imageView.images是否已存在于我分配给它的本地结构中,但这似乎无法正常工作。

是否有一种简单的方法告诉cellForItemAt“对于已有图像的细胞,不要寻找更多”?

这是我目前的代码:

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath as IndexPath) as! CollectionViewCell

        // Get images = using the URL
        FlickrClient.sharedInstance().getImagesFromFlickr(latitude: selectedPin.lat, longitude: selectedPin.lon, page: pageCount) { (pin, error) in

            if let pin = pin {
                let url = pin.images[indexPath.item].imageURL
                let data = try? Data(contentsOf: url)
                performUIUpdatesOnMain {
                    cell.imageView.image = UIImage(data: data!)
                    cell.imageView.contentMode = .scaleAspectFill
                }
            }
        }
    return cell
}

1 个答案:

答案 0 :(得分:0)

使用SDwebImage libray从网址加载图片。

https://github.com/rs/SDWebImage

在行的单元格上调用类似的东西:

let url = pin.images[indexPath.item].imageURL
cell.imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholder.png"))
相关问题