Time for a code snippet post.
If you have collection or table view that can change in unpredictable ways, and you wish to animate the changes, then you will usually use the
performBatchUpdates method of UICollectionView and UITableView.
This method takes a block, and in that block you are expected to account for all the changes in your datasource. For instance, if the number of elements returned in a section is 20 and after the performBatchUpdates-call its 10, they you are required to either delete 10 rows or items within that block, or delete 11 and add 1, or delete 20 and add 10, and so forth. The numbers must add up, otherwise your app will crash with an
NSInternatlInconsistencyException. (You can theoretically catch it but I haven’t tried because I suspect it will lead to many odd bugs if you do.)
Ok, so I googled for a generic way to calculate the necessary accounting, and I found this answer on StackOverflow.
The StackOverflow soltuon is presented in pseudocode, so here’s how it would look like with Swift.
So as you can see there’s an enum called
ArrayAction that represents the rows/items added, deleted and moved. Here’s how I use that method in my ViewController:
And that private method is used like that:
And that’s pretty much it.
Where do I use this code and might it have anything to do with the title picture? Glad you asked. :P
It’s used in Poly Art, a game a friend and I made for iOS. It’s free to play and we’d be happy if you gave it a try!
(I really had a hard time calculating the deltas in the game, because I stubbornly avoided the generic solution. Instead I was trying to anticipate what changes were possible, but as any programmer sooner or later learns: Even the simplest things can get very difficult if you use just a few of them combined.)
P.S.: You can follow me on Twitter.