UICollectionView with Snapping and Scaling in Swift

Satsuki Hashiba
2 min readNov 14, 2020

--

In this post, I’ll describe how to build UICollectionView with snapping and scaling like Smart Stack in iOS 14.

At the end, you’ll have the following:

The finished project is available on GitHub.

Appearance

So first, create a custom collection view cell and register it to the collection view. I won’t explain everything in detail but you can browse all code on GitHub. Override collectionView(_:layout:sizeForItemAt:) and return the size of the collection view to display only one cell at the time.

In this step, you’ll get the following:

Custom Layout

We’ll get snapping and scaling effects by a custom layout class. Create a subclass of UICollectionViewFlowLayout and change the layout of the collection view to it.

Snapping a cell to the center

Override targetContentOffset(forProposedContentOffset:): a method to change the proposed content offset to use at the end of the animation. proposedContentOffset parameter represents the point that the collection view has calculated as the most likely value to stop scrolling. Tweak it and return the center of the closest cell to the proposed content offset.

Scaling while scrolling

To enable a layout update while scrolling, override shouldInvalidateLayout and return true.

Next, override layoutAttributesForElements(in:): returns the layout attributes for all items (cells and supplementary views) inside the given rectangle. Retrieve already computed layout attributes using the superclass’s method we are overriding, then tweak these. In this case, calculate a distance between the centers of the cell and the current visible rectangle and scale the cell depending on this value.

--

--

Satsuki Hashiba
Satsuki Hashiba

Written by Satsuki Hashiba

iOS Engineer 🍋 Master’s Student 🌄 Japan ⛩

Responses (1)