Swift 3:在 collectionView 中缓存图像 [英] Swift 3: Caching images in a collectionView

查看:28
本文介绍了Swift 3:在 collectionView 中缓存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理我的应用程序,将其更新为与 Swift 3 一起使用,但还剩下一个问题.以前,我的图像缓存工作得非常好,但是由于更新,在获取图像时没有填充 UIImageViews.

I'm currently working through my app, updating it to work with Swift 3 and have one problem left. Previously, my image caching worked really well, but since the update the UIImageViews aren't being populated when the image is fetched.

这是代码(在 ...cellForItemAt... 函数中):

Here is the code (in the ...cellForItemAt... function):

if let img = imageCache[imageUrl] {
    print("CACHE HIT: \(indexPath)")
    cell.image.image = img
} else {
    print("CACHE MISS: \(indexPath)")
    var imgUrl: = URL(string: imageUrl)
    let request: URLRequest = URLRequest(url: imgUrl!)
    let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
        if(data != nil) {
            print("IMAGE DOWNLOADED: \(imgUrl?.query))")
            let image = UIImage(data: data!) // create the image from the data
            self.imageCache[imageUrl] = image // Store in the cache
            DispatchQueue.main.async(execute: {
                if let cell = collectionView.cellForItem(at: indexPath) as? MyCollectionViewCell {
                    print("APPLYING IMAGE TO CELL: \(indexPath)")
                    cell.image.image = image
                    self.collectionView.reloadData()
                } else {
                    print("CELL NOT FOUND: \(indexPath)")
                }
            })
        } 
    }) 
    dataTask.resume()
}

如您所见,我添加了一些 print 以了解发生了什么.当视图加载时,我可以看到缓存未命中,图像加载和 UIImageView 为可见行填充,但是当我向下滚动时,UIImageView 是从未填充,并且日志为每个 indexPath 显示 CELL NOT FOUND: [0, x].

As you can see, I've added in some prints to find out what is going on. When the view loads, I can see cache misses, and the images loading and the UIImageViews being populated for the visible rows, however when I scroll down, the UIImageViews are never populated, and the log shows CELL NOT FOUND: [0, x] for each indexPath.

如果我在向下滚动后再次向上滚动,则会按预期从缓存中填充图像.

If I scroll up again after scrolling down, images are populated from the cache as expected.

自上一版 Swift/iOS/Xcode 以来,代码没有改变,并且曾经完美运行.

The code hasn't changed since the previous version of Swift / iOS / Xcode, and used to work perfectly.

我对任何 3rd 方扩展等不感兴趣;我想了解上面的代码有什么问题.不过,欢迎对代码提出任何其他改进/建议.

I'm not interested in any 3rd party extensions etc.; I want to understand what is wrong with the code above. Any other improvements/suggestions to the code however are welcome.

任何想法将不胜感激!

推荐答案

与其通过 cellForItem(at: indexPath) 方法获取单元格,不如使用 cell用于在缓存命中中设置图像的变量.这将创建对单元格图像视图的强引用.

Rather than getting the cell via the cellForItem(at: indexPath) method, just use the cell variable you use to set the image in the cache hit. This will create a strong reference to the cell's image view.

DispatchQueue.main.async(execute: { [weak collectionView] in
    cell.image.image = image
    collectionView?.reloadData()
})

考虑将您的 UIImageView 重命名为 imageView 而不是 image.

Consider renaming your UIImageView to imageView rather than image.

这篇关于Swift 3:在 collectionView 中缓存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆