ScrollView with AutoLayout
suggest changeSimple steps to use scrollview with autolayout.
- Create a new project with single view application
- Select the default viewcontroller and change its screen size to iPhone-4inch from attributes inspector.
- Add a scrollview to your viewcontroller’s view as follows and set background color to blue
- Add constraints on it as shown in below image
What this will do is,simply stick every edge of scrollview to viewcontroller’s view
Scenario 1:
Now lets say our content is huge,and we want it to scroll horizontally as well as vertically.
For this,
- Add a UIView to the scrollview of frame(0,0,700,700).Lets give it orange background color to identify it differently.
Next comes the important part,we need it to scroll horizontally and vertically.
- Select the orange view and add the following constraints
Let me explain what we did in above step.
- We fixed the height and width to 700.
- We set trailing space to scrollview = 0 which tells the scrollview that content is horizontally scrollable.
- We set bottom space to scrollview = 0 which tells the scrollview that content is vertically scrollable.
Now run the project and check.
Scenario 2: Lets consider a scenario where we know that content width is going to be same as scroll width width,but height is larger than scrollview.
Follow the steps to scroll content vertically.
- Delete the width constraint in above case.
- Change the width of orange view to match to scrollview width.
- Ctrl-drag from orange view to scroll view and add equal widths constraint.
- And Done!!! Simply run and check if it scrolls vertically
Scenario 3:
Now we want to scroll only horizontally and not vertically.
Follow the steps to horizontally scroll the content.
- Undo all the changes to achieve constraints as below(i.e restore original constraints which achieved vertical and horizontal scroll)
- Check frame of orange view,which should be (0,0,700,700)
- Delete height constraint of orange view.
- Change the height of orange view to match the scrollview height.
- Ctrl-drag from orange view to scroll view and add equal heights constraint.
- And Done!!! Simply run and check if it scrolls vertically
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents