Layout to Layout Transitions

Working with UICollectionView and the layout to layout transition makes it very easy to animate between two flow layouts with minimal work.

There are a couple of major gotchas that one needs to be aware of. The first is that the data source and delegate do not change. The initial view controller remains in charge.

Secondly, with custom subclasses of UICollectionViewCells that use autolayout to lay out their subviews, you need to override apply(layoutAttributes:) and call setNeedsLayout() in order to get those subviews to animate alongside the cells themselves.

Not doing this causes the cells to jump between their start and end state when the rest of the animation finishes.

Using Enums for Selected Items

Because the master collection view controller continues to be the data source, one nice thing I found is to use an enum for the selected section. This was inspired by this post by Soroush Khanlou.

The enum will either be none for no selected item, or a section index for a selected item:

The model can then read from a computed property that will return either all of the items or only the selected items:

The collection view uses this computed property as its data source for things like numberOfItems(inSection:).

This allows for some neat tricks where you can animate the addition or removal of all the other sections during the transition.

Because the computed property will now be updated to reflect only a single section, the collection view will animate the deletion of the sections nicely alongside the new layout transition, leaving the new layout with only a single section.

This is not ideal for complex detail views that allow for a lot of editing as the Master Collection View Controller is still in charge of all delegate and data source calls, but for a quick way of drilling down through a collection view hierarchy, it can save a lot of time and effort.

  • Share:

Get all of my latest posts direct to your inbox! Pop in your email address here: