swift 4,如何在collectionView中加载超过3000~张图片?

标签 swift collectionview

我正在使用UICollectionView为了一张专辑。 我在 iPhone 7 上加载了图片。我让它加载了大约 2000 张图片,但是如果当我滚动 UICollectionView 时有超过 3000 张图片。下来速度非常慢,有时应用程序会停止。

我正在使用此代码来获取图片。

extension UIImageView {
    func fetchImage(asset: PHAsset, contentMode: PHImageContentMode, targetSize: CGSize) {
        let options = PHImageRequestOptions()
        options.version = .original
        options.isSynchronous = true
        PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: contentMode, options: options) { image, _ in
            guard let image = image else { return }
            switch contentMode {
            case .aspectFill:
                self.contentMode = .scaleAspectFill
            case .aspectFit:
                self.contentMode = .scaleAspectFit
            }
            self.image = image
        }
    }
}

我做了一个let imageCache = NSCache<NSIndexPath, UIImage>() 并在 cellForItem 中使用它。但这并没有解决这个问题。 还有其他方法可以做到这一点吗?

而且我连续得到 3 张图片,大小为 self.view.frame.width / 2

如果没有办法的话。我必须获得较小尺寸的图像吗?

cellForItem代码:

let imageCache = NSCache<NSIndexPath, UIImage>()

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "albumCell", for: indexPath) as? AlbumCollectionViewCell

    let asset: PHAsset? = AlbumModel.allPhotos?.object(at: indexPath.row)

    cell!.albumImageView.contentMode = .scaleAspectFill
    if let fromImageCache = imageCache.object(forKey: indexPath as NSIndexPath) {
        cell!.albumImageView.image = fromImageCache
        return cell!
    }

    let setSize = CGSize(width: view.frame.width / 2, height: view.frame.width / 2)
    cell!.albumImageView.fetchImage(asset: asset!, contentMode: .aspectFill, targetSize: setSize)

    imageCache.setObject(cell!.albumImageView.image!, forKey: indexPath as NSIndexPath)
    return cell!
}

最佳答案

以下是一些提高滚动浏览照片库时性能的提示:

不要实现您自己的图像缓存或使用默认图像管理器,请使用您自己的 PHCachingImageManager 实例。您可以告诉它开始缓存滚动位置周围的图像以提高性能。

不要使用同步获取图像。使用异步方法并更新完成 block 中的 ImageView ,但请注意,完成 block 甚至可以在 fetch 方法返回之前触发,并且当您从库中获取质量更好的图像时多次触发。

当单元格离开屏幕时取消提取。

我已经有一段时间没有使用该框架了,但我写了一些关于它的笔记 here希望这些仍然具有相关性。

关于swift 4,如何在collectionView中加载超过3000~张图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53848706/

相关文章:

ios - 使用当前时间戳查询该时间之前的所有帖子

带有方形图像的 Xamarin Forms CollectionView

swift - 如何使用向右滑动的手势执行 segue

ios - 在 View Controller 的单个 Collection View 中显示多个图表,如条形图、饼图、折线图

macos - 根据变量 swift 调整窗口大小

swift - Swift 中导入 NS_OPTIONS (RawOptionSetType) 的 Switch 语句?

ios - 如何删除 Storyboard中 UIView 的底部空白区域?

ios - 根据用户在 swift 中输入的数组创建键值对

ios - 如何为其他设备显示我的自定义 Collection View

ios - 滚动 Collection View 时,cellForItemAt indexPath 会出现问题