iOS UICollectionView Performing batch updates

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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:

TypeNSIndexPath
InsertionIndex in new array
DeletionIndex in old array
Movefrom: old array, to: new array
Reloadeither 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)


Got any iOS Question?