執行批量更新
你可以使用 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)