Scrollview autolayout constraint setup in Xcode

This seems to be quite a common issue for people using the Interface Builder and AutoLayout in Xcode to manage a ScrollView. The main headache that people encounter is the Scrollview just doesn’t scroll, which is pretty useless. But the solution for this is actually pretty simple, it just takes a bit if tinkering to get it right.

Firstly, you want to put all your content inside a View and then embed that view in the Scrollview. In your inspector, the hierarchy would look like the image below:

Screen Shot 2015-12-11 at 15.29.29

The “Scroll View” here has only one child, everything else that appears in the Scroll view should be a child of this “View”.

The next thing you want to do is add constraints to the top, bottom, trailing and leading spaces on the Scrollview:

Screen Shot 2015-12-11 at 15.32.36

Now comes the interesting part, you need to set a constraint on the “View” child in Scrollview to be equal widths to the main View in your ViewController. To do this, ctrl drag from the child View to the main View, and select “Equal Widths” on the popup that appears:

Screen Shot 2015-12-11 at 15.37.18

Next, ctrl drag from the View to the ScrollView, and add constraints for top, bottom, trailing and leading as we did earlier.

If you were to run your app now, everything would appear correctly, but the ScrollView would still not scroll. This is because we need to tell the child View how high it is. This is the important bit. We do this by adding a “Bottom Space to Container” constraint on the bottom child element of the View. In the image below, our bottom element is a button called Finish:

Screen Shot 2015-12-11 at 15.41.28

In the image above, I have ctrl dragged from the button “Finish”, to the parent view, “View”, and selected the “Bottom Space to Container” constraint. Run your app now, and you should have a fully working ScrollView constructed with AutoLayout!

The important thing to remember is whatever element you have at the bottom, make sure you set a bottom constraint to the parent view. In the example above, if I were to add another button below the “Finish” button, I would have to remove the bottom constraint (to parent view) on the “Finish” button, and add a bottom constraint (to the parent view), on the new button I had just added.

Leave a comment