Buddybuild is a CI, CD and user feedback platform built for mobile development teams - sign up for free and start building better apps!

Today we'll continue our look at UICollectionView by diving into animation. Let's begin.

We'll start with the same simple baseline collection view controller we made at the beginning of Bite #306.

Now, we'll add two new collection view layouts to our view controller:

var small: UICollectionViewFlowLayout = {
  let layout = UICollectionViewFlowLayout()

  layout.itemSize = CGSize(width: 75, height: 75)

  return layout
}()

var big: UICollectionViewFlowLayout = {
  let layout = UICollectionViewFlowLayout()

  layout.itemSize = CGSize(width: 150, height: 150)

  return layout
}()

Then, we'll override init on our view controller, and hand it our "small" layout:

init() {
  super.init(collectionViewLayout: small)
}

Nice. At this point we have a basic collection view controller, scrolling our small cells:

Now, we'll add some code to toggle between our two layouts when the user taps any cell:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  let newLayout = (collectionView.collectionViewLayout == small ? big : small)

  collectionView.setCollectionViewLayout(newLayout, animated: true)
}

Now we can toggle back and forth between our two layouts with a nice looking animation. Very cool.

It's super handy how the setCollectionViewLayout function is smart enough to alter the animtion so the cell we selected is still in view once the animation completes.

We can see this effect exaggerated when we bump up the itemSize of our "big" layout:

var big: UICollectionViewFlowLayout = {
  let layout = UICollectionViewFlowLayout()

  layout.itemSize = CGSize(width: 300, height: 300)

  return layout
}()

Nice!

Download the Xcode project we built in this Bite right here.

One final note here: This just one approach. There are tons of different ways to achieve this (and similar) behavior. We'll take a look at more as we dive deeper into collection views in upcoming Bites.

Have a specific UICollectionView question you'd like answered? Send it along!.