You can animate complex changes to your collection view using the performBatchUpdates
method. Inside the update block, you can specify several modifications to have them animate all at once.
collecitonView.performBatchUpdates({
// Perform updates
}, nil)
Inside the update block, you can perform insertions, deletions, moves, and reloads. Here is how to determine which indexPath to use:
Type | NSIndexPath |
---|---|
Insertion | Index in new array |
Deletion | Index in old array |
Move | from: old array, to: new array |
Reload | either new or old array (it shouldn't matter) |
You should only call reload on cells that have not moved, but their content has changed. It is important to note that a move will not refresh the content of a cell, but only move its location.
To verify that your batch update will be performed correctly, make sure the set of indexPaths for deletion
, move-from
, and reload
are unique, and the set of indexPaths for insertion
, move-to
, and reload
are unique.
Here's an example of a proper batch update:
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)