ios - 如何在滚动时停止在 Collection View 中重新加载服务器图像?

标签 ios swift uicollectionviewcell

我正在使用带有图像的 Collection View 。可以说,它有 30 张图像。 每当我 ScrollView 时,图像就会重新加载。这是因为,每当我滚动时,都会调用此函数。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 现在我的问题是:我从 facebook 获取了一些图像,从数组中获取了一些图像。因此,每当我滚动时,来自 Facebook 的图像都会重新加载。我怎样才能停止重新加载这些图像。

这是我显示图像的代码(来自 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加载图像。它为您进行加载和缓存。

关于ios - 如何在滚动时停止在 Collection View 中重新加载服务器图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35934309/

相关文章:

IOS SDK + Youtube API + NoLinkedYouTubeAccount

ios - Swift 中的 parser.parse() 导致 EXC_BAD_ACCESS

ios - 如何以编程方式快速设置自动布局中的 UIView 大小?

ios - CollectionViewCell 中的PrepareForReuse

php - AFNetworking 将 UIImage 上传为 NSData -> PHP 脚本移动文件

ios - 未上传开发 APNs 证书

xcode - 是否可以检查 Swift 2.1 中的目录是否为空?

objective-c - 无法构建 Objective-c 模块?

ios - 如何在收藏 View 中显示复选标记(图像)

ios - UICollectionView reloadData 看起来很慢/滞后(不是即时的)