Fun with auto-layout and scrollview
This post covers the basics of using auto-layout and scrollview. So with the advent of bigger screen iPhones it has become (not just almost but completely) important to understand the mechanics of auto-layout. So I hope you will find this post useful incase you are having difficulty using scrollview and auto-layout.
Here is the complete process assuming you want vertical scrolling:
- enable auto-layout
- add a scrollview anywhere using storyboard or xib
- add 4 constraints on scrollview (all with respect to its superview)
- left
- right
- top
- bottom
- add a container view (a UIView basically) into scrollview
- add 5 constraints to the container view (all with respect to its superview i.e. scrollView)
- left
- right
- top
- bottom
- fixed width (if you want vertical scrolling)
- DON’T add the 6th constraint i.e. height as it will be automatically calculated by the xcode depending on its subviews
- add subviews inside the container view that you want to get scrolled
Now lets say you want to add 3 subviews each of height 400px (total = 1200px)
- add 4 constraints to the first subview (inside container view)
- left
- top (zero or more only with respect to container view)
- height
- width
- add 4 constraints to the second subview (inside container view)
- left
- top (zero or more only with respect to first subview)
- height
- width
- add 5 constraints to the second subview (inside container view)
- left
- top (only with respect to second subview)
- height
- width
- bottom (zero or more only with respect to container view)
Now if everything went as planned then your container view height will automatically increase to 1200px or more in the xib/storyboard.
Now why this works ?
- so the first subview has the top constraint with the container and the last subview has the bottom constraint with the container. The second subview is fixed in between the first and last subview stretching the constraint elastic.