UICollectionView Custom Layout: the Ultimate Tutorial – Part 2

Welcome back to the “UICollectionView Custom Layouts: the Ultimate Tutorial” series. This is Part 2, where we will actually tackle the custom layout part.
If you haven’t seen or done the first part, I strongly recommend you to take a look at it, as we will be using the UICollectionView we created there.

Remember what we had at the end of Part 1, when we run the project without the custom layout, and what we would like to achieve?

CollectionView without UICollectionViewFlowLayout       Wireframe of the CollectionView with UICollectionViewFlowLayout

A few words

A few words before we start:

I recommend you to have a look at Session 232 of WWDC 2014: Advanced User Interfaces with Collection Views for the Custom Layout questions, and at Session 226 of WWDC 2014: What’s new in Table and Collection Views concerning the cell sizing. I won’t go into the details here as everything is well explained on the videos.
Here, we will focus on the implementation.

Preparing the cells

First, we need to add a bit of code in the TextCell class, as this cell will need to get resized. Simply paste the following code in TextCell.swift

Let’s add a simpler version of it in the ItemCell class:

This part of the code enables the Layout to calculate the new size of the cell, matching its content.

You don’t need similar code for ImageCell because its size is fixed, set in the custom layout and not re-calculated.

And now, take a deep breath, we will create the long-awaited custom layout!

UICollectionViewFlowLayout

Let’s start with the first baby step:

Create a new file, subclass of UICollectionViewFlowLayout and name it MyCollectionViewFlowLayout.

Then, let’s add some configuration: section variables, initializations and basic setup.

Also, don’t forget to add the class in the Collection View attributes in the Storyboard. Select “Custom” and type “CustomCollectionViewLayout” in the class field. Obvious, but oh so easy to forget ;)

PrepareLayout

Now, let’s tackle the heart of the problem custom layout:

The first function to create is prepareLayout, which, as its name states, prepares the layout.

The documentation says :

“Tells the layout object to update the current layout.
Layout updates occur the first time the collection view presents its content and whenever the layout is invalidated explicitly or implicitly because of a change to the view. During each layout update, the collection view calls this method first to give your layout object a chance to prepare for the upcoming layout operation.
The default implementation of this method does nothing. Subclasses can override it and use it to set up data structures or perform any initial computations needed to perform the layout later.”

In this function, we will loop over the sections and items to get the actual size of each element, and to keep track of the height of the content.
And as we would like to have a code as elegant as possible, we will do the size calculation in a separate function, called frameForItemAtIndexPath.

Then, we will make sure that the UICollectionView has the right size:

Pretty straight forward.

Layout Attributes

Two more thing and we’re done! Now that we have calculated the size of the cells and that we know the size of the UICollectionView, we can determine the attributes, ie what will appear on screen in a rect or at a certain indexPath:

Should invalidate layout

And the last step to finalize the layout: we want to invalidate the layout when needed, ie make sure the cells are calculated according to the actual space available, and not according to the layout estimated size.

I hope this tutorial series helped a bit. As I said at the beginning, I tried to cover different cell configurations to give you the tools to start experimenting with custom layouts, now it’s up to you to go further! And, who knows, maybe Apple will soon release something to help us deal (easily) with variable height in UICollectionViewCells like they did for UITableView

All the code for this tutorial is available on GitHub: SCCollectionViewCustomLayout. As usual, don’t hesitate to fork it and play with it! Also, there is a little bonus: I’ve included a dynamic HeaderView in the UICollectionView and Custom Layout :) You’re welcome!

If you have read that far, thank you! Really! I know it has been long, but you won’t go unrewarded, I have some extra tips to share with you :)

Pro tips:

  • Try it on the iPad, it’s responsive! (if you add viewWillLayoutSubviews() to the UIViewController, like in the example on GitHub)
  • If you are caught in an infinite loop in the UICollectionViewFlowLayout that makes the app crash, double check the size (and potential margins) of the cells you are trying to render. If it doesn’t match with the available space, it will try to calculate it again until it fits, which isn’t likely to happen… and it will eventually crash.

3 thoughts on “UICollectionView Custom Layout: the Ultimate Tutorial – Part 2

  1. xCode 8 ios 10.3 Crash -> Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘the invalidation context ((null)) sent to -[UICollectionViewFlowLayout invalidateLayoutWithContext:] is not an instance of type UICollectionViewFlowLayoutInvalidationContext or a subclass’

Leave a Comment

You want to leave a comment? Sweet! Please do so, but keep in mind that all comments are moderated and rel="nofollow" is in use. So no fake comment or advertisement will be approved. And don't worry, your email address won't be published. Thanks!

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">