执行批量更新
你可以使用 performBatchUpdates 方法为集合视图的复杂更改设置动画。在更新块内,你可以指定多个修改以使它们一次全部动画。
collecitonView.performBatchUpdates({
// Perform updates
}, nil)
在更新块内,你可以执行插入,删除,移动和重新加载。以下是如何确定要使用的 indexPath:
| 类型 | NSIndexPath |
|---|---|
| 插入 | 新数组中的索引 |
| 删除 | 旧数组中的索引 |
| 移动 | from:old array,to:new array |
| 刷新 | 无论是新阵列还是旧阵列(都应该没关系) |
你应该只对未移动的单元格调用 reload,但其内容已更改。重要的是要注意移动不会刷新单元格的内容,而只会移动其位置。
要验证是否正确执行批量更新,请确保 deletion,move-from 和 reload 的 indexPaths 集是唯一的,insertion,move-to 和 reload 的 indexPaths 集是唯一的。
以下是正确批量更新的示例:
let from = [1, 2, 3, 4, 5]
let to = [1, 3, 6, 4, 5]
collecitonView.performBatchUpdates({
collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: 2, inSection: 0)])
collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: 1, inSection: 0)])
collectionView.moveItemAtIndexPath(NSIndexPath(forItem: 2, inSection: 0),
toIndexPath: NSIndexPath(forItem: 1, inSection:0))
}, nil)