Scroll View + Auto Layout in Xcode 8
I used to have a hard time when it came to using Scroll Views because of the Auto Layout constraints. I just couldn’t make it look and feel the way it was supposed to look and feel. But luckily, I have figured them out now.
I will be showing you how to create a Scroll View with a few elements inside that will look good no matter the device it’s being opened in. There are not going to be Navigation Controllers, Tab Bar Controllers, Table View Controllers, etc. in this example. A Scroll View in a View Controller. That’s it. The constraints change a little bit otherwise, but it would follow the same pattern.
Create the project
If you haven’t already 🙄
Add a Scroll View
The View Controller will only have a Scroll View. In this example, it will be occuping the entire screen, so I added top, bottom, leading and trailing constraints to the parent View.
Add inner view
This View will be the only child of the Scroll View. It has top, bottom, leading and trailing constraints to the Scroll View. But the most important constraints are the equal heights and equal widths to the main View.
Change equal heights’ priority
Locate the equal heights constraint and change its priority to 250.
Start adding elements
The constraints are ready for you to start doing what you want to do. But remember to add the elements to the child of the Scroll View, not to the Scroll View itself!
But, hey! What happens if you want to add elements even lower within the View? 🤔
Change the top constraint of the Scroll View’s only child to -200 (or anywhere lower than 0), change the height of the View and add the new element with its corresponding constraints.
Update top constraint
Change the top constraint back to normal.
Keep on adding elements as if it were a simple View, but remember to change the top constraint of the Scroll View’s only child.
Please do let me know if you have any comments or if this was of any help at all.