Step 2 — Constrain a Collection View with NSLayoutConstraint within a subview hierarchy ✅

I won’t explain collection views in this article too much. If you want to learn more about collection views, read this article.

I do, however, want to explain those constraints. This is how you do the Auto Layout’s without storyboards, it’s how you do Auto Layout with pure code!

Explanation

To get this to work, you have to add the UIView, in this case, the UICollectionView to a set of subviews. If you try and activate constraints before adding the view to a view hierarchy, the app will crash because you can’t constrain something on a screen, if it’s not on the screen first.

Metaphor

Another way to put it; you can’t attach your hand to someone else’s hand unless they are in the room with you. The room being a UIView subview hierarchy, and our hands being either a top, bottom, leading, or trailing NSLayoutConstraint.

Constrained

We now have a constrained UICollectionView with a height of 400 points, and constraints attaching it to the bottom of our UINavigationController header, and the sides of our viewController view.