我在主捆绑中有大约100个GIF。我在一个数组中的viewDidLoad()期间加载所有内容。此数组是UICollectionView的数据源。问题是这些GIF占用了大量内存,导致内存缓慢并导致应用程序崩溃。当我开始滚动时,内存调试器显示最多800 mb +然后崩溃。
我考虑集成第三方库来优化GIF的性能。然后我考虑创建某种本地缓存解决方案,我可以卸载内存,并在单元格离开时在后台需要时获取数据。这是一种正确的方法还是我过于复杂的事情?
viewDidLoad
中加载gif包网址(仅限网址,而不是图片数据)。override func viewDidLoad() {
gifUrls = ...
}
// In collection view cell
imageView = BBAnimatedImageView(frame: frame)
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
}
}
}
正如@rmaddy所说,你可以通过这些方法在可见单元的循环中加载GIF:
func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath)
和:
func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath)\
在willDisplay
上加载gif并在didEndDisplaying
上卸载它。