You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UICollectionView最后一个Cell移动后删除Section无动画问题求解

解决UICollectionView移动最后一个Cell并删除Section时的动画问题

这个问题我之前也碰到过,核心原因是在同一个performBatchUpdates块里同时执行moveItem和deleteSections,当移动的是第一个section的最后一个cell时,UICollectionView的内部布局状态会出现冲突,导致删除section的动画被跳过,甚至完成回调都不触发。

修复方案

我们需要把删除section的操作和移动cell的操作分开执行,先完成cell移动的动画,在它的completion回调里再执行删除section的batch更新,这样就能保证两个动画都能正常展示,同时回调也能正常触发。

修改后的代码如下:

let oldIndexPath = self.indexPathForAsset(asset)
self.collectionView.performBatchUpdates({
    // 先更新数据源,执行移动操作
    let newIndexPath = self.indexPathForAsset(asset)
    self.collectionView.moveItem(at: oldIndexPath, to: newIndexPath)
}, completion: { [weak self] finished in
    guard let self = self, finished, self.numberOfCollectionViewSections() == 1 else { return }
    // 在移动完成后,单独执行删除section的batch更新
    self.collectionView.performBatchUpdates({
        self.collectionView.deleteSections([0])
    }, completion: nil)
})

为什么这样有效?

  • 分开执行两个batch操作,避免了UICollectionView在处理move和delete时的状态冲突,确保每个动画都能被系统正确识别和执行。
  • 利用第一个batch的completion回调,我们可以确认移动操作已经完成,此时第一个section已经没有任何cell,再执行删除section的操作,动画会自然流畅地展示。
  • 加上finished判断,确保只有当移动操作真正完成后才执行删除,避免不必要的操作。

另外还要注意,你的数据源方法(比如numberOfSections、numberOfItemsInSection)在每次batch更新后都要返回正确的值,这是UICollectionView动画正常工作的核心前提。

内容的提问来源于stack exchange,提问作者BlackWolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:28:00