从Bundle.main向UICollectionView加载/清除数据的理想方法是什么?

问题描述 投票:-2回答:2

我在主捆绑中有大约100个GIF。我在一个数组中的viewDidLoad()期间加载所有内容。此数组是UICollectionView的数据源。问题是这些GIF占用了大量内存,导致内存缓慢并导致应用程序崩溃。当我开始滚动时,内存调试器显示最多800 mb +然后崩溃。

Crash

我考虑集成第三方库来优化GIF的性能。然后我考虑创建某种本地缓存解决方案,我可以卸载内存,并在单元格离开时在后台需要时获取数据。这是一种正确的方法还是我过于复杂的事情?

ios swift uicollectionview gif collectionview
2个回答
2
投票
  1. viewDidLoad中加载gif包网址(仅限网址,而不是图片数据)。
override func viewDidLoad() {
    gifUrls = ...
}
  1. 在集合视图单元格中使用第三方视图来显示gif。例如,我们使用BBWebImage
// In collection view cell
imageView = BBAnimatedImageView(frame: frame)
  1. collectionView(_:cellForItemAt:)中异步加载gif。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseID, for: indexPath)
    cell.tag = indexPath.item
    let url = gifUrls[indexPath.item]
    DispatchQueue.global().async {
        guard let data = try? Data(contentsOf: url) else { return }
        let gif = BBAnimatedImage(bb_data: data)
        DispatchQueue.main.async {
            guard cell.tag == indexPath.item else { return }
            cell.imageView.image = gif
        }
    }
}

1
投票

正如@rmaddy所说,你可以通过这些方法在可见单元的循环中加载GIF:

func collectionView(_ collectionView: UICollectionView, 
             willDisplay cell: UICollectionViewCell, 
               forItemAt indexPath: IndexPath)

More details

和:

func collectionView(_ collectionView: UICollectionView, 
        didEndDisplaying cell: UICollectionViewCell, 
               forItemAt indexPath: IndexPath)\

More details

willDisplay上加载gif并在didEndDisplaying上卸载它。

© www.soinside.com 2019 - 2024. All rights reserved.