UIScrollView Auto Layout With SnapKit

Ditching storyboard and building views programatically can be a big step. Auto layout is incredibly useful, but the api can still be a little fiddly at first. There are a number of third part libraries to make life easier, and I’m a big fan of SnapKit.

One thing that that can still trip people up (myself included) is working with UIScrollViews. The important thing to keep in mind is that a scroll view needs to know its content size.

First off lets assume that the scroll view will take up the full screen:

A solution is to add another view to the scroll view that will act as a container for all the other views it contains. This is just a standard UIView, we’ll name it contentView:

All other views will be added to the contentView.

The key is to provide enough constraints so that the contentSize of the scroll view can be calculated automatically.

For example: