Animate Changes in UICollectionView

Step-by-step practical guide on creating custom animations in UICollectionView

Ruslan Dzhafarov
5 min readApr 9, 2024
Design by Mahdi Mozafari (Behance)

UICollectionView offers a versatile framework for displaying collections of items in iOS applications. While its built-in animations for insertion and deletion are functional, incorporating custom animations can take your user interface to the next level of sophistication. In this tutorial, we’ll explore how to implement custom animations for insertion and deletion in UICollectionView, adding a touch of elegance to your app’s user experience.

Step 1: Create a Custom Layout Subclass

The foundation of custom animations in UICollectionView lies in subclassing UICollectionViewLayout. This subclass allows you to define the layout and behavior of items within the collection view. We'll use this subclass to override key methods responsible for managing the layout and animations of items.

class CustomCollectionViewLayout: UICollectionViewLayout {}

Step 2: Prepare Data for Animations

To begin customizing animations, we override the prepare(forCollectionViewUpdates:) method in our UICollectionViewLayout subclass. This method is called before any animations are performed, giving us the opportunity to determine which items are being inserted, deleted, or moved within the collection view.

According to Apple’s Documentation:

When items are inserted or deleted, the collection view notifies its layout object so that it can adjust the layout as needed. The first step in that process is to call this method to let the layout object know what changes to expect. After that, additional calls are made to gather layout information for inserted, deleted, and moved items that are going to be animated around the collection view.

private var indexPathsToInsert: [IndexPath] = []
private var indexPathsToDelete: [IndexPath] = []

override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
super.prepare(forCollectionViewUpdates: updateItems)

indexPathsToDelete = updateItems.filter { $0.updateAction == .delete }.compactMap { $0.indexPathBeforeUpdate }
indexPathsToInsert = updateItems.filter { $0.updateAction == .insert }.compactMap { $0.indexPathAfterUpdate }
}

This code snippet extracts the index paths of items being inserted, deleted, or moved, allowing us to customize their animations accordingly.

When an item is being deleted, indexPathBeforeUpdate will hold the index path of the item before the deletion. Conversely, when an item is being inserted, indexPathAfterUpdate will contain the index path where the new item will be inserted. This differentiation is crucial for accurately orchestrating custom animations tailored to each specific action.

Step 3: Implement Insertion Animations

Next, we override initialLayoutAttributesForAppearingItem to add custom animations for inserted items.

According to Apple’s Documentation:

This method is called after the prepare(forCollectionViewUpdates:) method and before the finalizeCollectionViewUpdates() method for any items that are about to be inserted. Your implementation should return the layout information that describes the initial position and state of the item. The collection view uses this information as the starting point for any animations. (The end point of the animation is the item’s new location in the collection view.)

override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attrs = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath)

guard indexPathsToInsert.contains(itemIndexPath) else {
return attrs
}

// Rotate by 180 degrees
attrs?.transform = CGAffineTransform(rotationAngle: CGFloat.pi)

// Center at the bottom of the collection view
attrs?.center = CGPoint(x: collectionView.bounds.midX, y: collectionView.bounds.maxY)

return attrs
}

Here, we apply custom transformations to the layout attributes of inserted items, creating visually appealing animations.

Step 4: Implement Deletion Animations

Next, we override finalLayoutAttributesForDisappearingItem to add custom animations for deleted items.

According to Apple’s Documentation:

This method is called after the prepare(forCollectionViewUpdates:) method and before the finalizeCollectionViewUpdates() method for any items that are about to be deleted. Your implementation should return the layout information that describes the final position and state of the item. The collection view uses this information as the end point for any animations. (The starting point of the animation is the item’s current location.)

override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attrs = super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath)

guard indexPathsToDelete.contains(itemIndexPath) else {
return attrs
}

// Translate to the left by the width of the collection view
attrs?.transform = CGAffineTransform(translationX: -collectionView.bounds.width, y: 0)

return attrs
}

Here, we apply custom transformations to the layout attributes of deleted items, creating visually appealing animations.

Step 5: Finalize Animation Logic

Finally, we override finalizeCollectionViewUpdates to clear the data once the updates are completed. This ensures that our animation logic remains consistent throughout subsequent updates.

According to Apple’s Documentation:

The collection view calls this method as the last step before proceeding to animate any changes into place. This method is called within the animation block used to perform all of the insertion, deletion, and move animations so you can create additional animations using this method as needed. Otherwise, you can use it to perform any last minute tasks associated with managing your layout object’s state information.

override func finalizeCollectionViewUpdates() {
super.finalizeCollectionViewUpdates()

indexPathsToDelete = []
indexPathsToInsert = []
}

With these steps completed, your UICollectionView will now showcase custom animations for item insertion and deletion, enhancing the overall user experience of your iOS application.

Conclusion

In conclusion, mastering custom animations in UICollectionView allows developers to create dynamic and engaging user interfaces that captivate and delight users. By leveraging the flexibility and power of UICollectionViewLayout subclasses, you can tailor animations to suit the unique design requirements of your app, setting it apart from the competition. So go ahead, experiment with custom animations, and elevate your UI design to new heights!

If you want to dive deeper into UICollectionView and custom animations, here are some valuable resources:

Thank you for reading until the end. If you have any questions, please feel free to write them in the comments.

If you enjoyed reading this article, please press the clap button 👏 . Your support encourages me to share more of my experiences and write more articles like this. Follow me here on medium for more updates!

Happy coding! 😊👨‍💻👩‍💻

--

--

Ruslan Dzhafarov

Senior iOS Developer since 2013. Sharing expert insights, best practices, and practical solutions for common development challenges