如何在滚动时停止在集合视图中重新加载服务器图像



我正在使用带有图像的集合视图。比方说,它有 30 张图像。每当我滚动视图时,图像都会重新加载。这是因为,每当我滚动时,都会调用此函数。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 现在我的问题是:我从Facebook上获取很少的图像,从数组中获取很少的图像。因此,每当我滚动时,仅来自fb的图像都会重新加载。如何停止重新加载这些图像。

这是我用于显示图像的代码(来自 fb 和本地):

let task = NSURLSession.sharedSession().dataTaskWithURL(searchURL) { (responseData, responseUrl, error) -> Void in
        if let data = responseData{
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.image!.image = UIImage(data: data)
                if(cell.image!.image == nil){
                    let strid : String = friendInfo.Friendfb_id;
                    let facebookProfileUrl = NSURL(string: "https://graph.facebook.com/(strid)/picture?type=large")
                    cell.image!.url = facebookProfileUrl;
                }else{
                    cell.image!.url = searchURL;
                }
            })
        }
    }
    task.resume()

我还在单元格中设置了prepareForReuse

override func prepareForReuse() {
    self.imageView.image = nil
}

您必须实现某种缓存来缓存图像,因此当第二次显示同一单元格时,应从缓存而不是从服务器加载图像。实现这样的缓存有多种解决方案,我个人最喜欢的是使用 AlamofireImage 加载图像。它为您完成加载和缓存。

最新更新