UICollectionView with autosizing cell using autolayout in iOS 9 & 10

When you are developing iOS app. You will usually come across an app that use vertical card design like in the screenshot below.

If you familiar with iOS Apps developing. You will know that you have 2 choices to go. Use either UITableView or UICollectionView. In this tutorial I will go with UICollectionView because it’s more scalable than UITableView and you can adopt multi column in iPad if you want to.

In WWDC 2016 video session 219 : What’s New in UICollectionView in iOS 10. Apple said that there are 3 methods for collection view cell size from the screenshot below

In this tutorial we will go with method 1 Auto Layout. Let’s start

First setup your view controller and your UICollectionView. Name your UICollectionView outlet as “collectionView” pin constraint to 4 sides of your viewController

Since we will not use collection view cell in storyboard (We will use from nib instead) so we will set number of items in collection view to 0 and make sure that Layout is “flow” because we will use collection view flow layout to make the cell autosized.

Next create a class for collection view cell and xib of it. In this tutorial we name it Cell.swift and Cell.xib

Don’t forget to register nib as cell in viewDidLoad. We also set estimateItemSize for UICollectionViewFlowLayout to (1,1) because flowLayout will use auto sizing via auto layout when estimate item size has been set (This is the common pitfall).

Now it’s time to design your cell in Cell.xib set your cell size to the largest width you want it to be (> 414 is safe for 5.5 inch screen) if you set the width too low the app will crash at runtime (ex. you set width to 350 it will crash on 5.5 inch screen) and add some height to it too (Note that this dimension is just for design time)

Put a UIView as a container for all view your cell pin 4 side to cell.

Next we design our cell as follow. Make sure that your bottommost view and rightmost pin to container view. This is required for cell to be autosizing.

Then we make outlet to cell class

create constraint for container view width and make outlet to cell class too

Then set the content view width constraint to match the screen size in awake from nib substract collection view inset that you set in storyboard. We also set self.contentView.translatesAutoresizingMaskIntoConstraints = false to prevent Xcode from generating auto layout constraint for width and height of cell that we don’t need.

Now we should test it by adding datasource to collection view as usual and run

Running on retina 4 inch
Running on retina 4.7

Sample project here : https://github.com/tttsunny/CollectionViewAutoSizingTest