Giles Van Gruisen

UICollectionViewFlowLayout animation timing

Issue 12 of Objc.io has some awesome resources on dealing with animations on iOS. In particular, I found the article on Animating Collection Views to be incredibly helpful.

There's a great section on defining custom to/from animation states for animating cells, but those animations are interpolated linearly and seem to have a hardset duration. Notably missing was any way to manipulate the interpolation or duration of these animations.

More specifically, I was looking for a way to use springs to animate the insertion of new cells. I tried to dig around StackOverflow and elsewhere with no luck. Then I had an idea: what if I made the call to insertItemsAtIndexPaths inside a UIView animation block?

"No way that'll work," I thought to myself, but I've learned better than to just move on when I doubt something will work. I tried it out and, to my utter surprise, it worked! Here's an example.

Example

UIView.animateWithDuration(0.5,  
    delay: 0.0, 
    usingSpringWithDamping: 0.7, 
    initialSpringVelocity: 0.0, 
    options: .CurveEaseInOut, 
    animations: {
        self.collectionView.insertItemsAtIndexPaths(indexPaths)
    },
    completion: nil )

Remember, you'll still need to define your custom to/from animation states in a UICollectionViewFlowLayout subclass. Learn more about that in the Objc.io article.