How to configure a UIScrollView using Auto Layout in Interface Builder/XIB.
As an iOS developer, we stuck on UIScrollView with dynamic width and height. Today we will be demonstrating you how to handle this easily. In this approach, we are doing this with storyboard only. As per your requirement create your design; desired height and as many as subviews; it will automatically take care all things.
Follow the below steps:
- Create a new Xcode Project
- Navigate to Main.storyboard file
- Select ScrollView from the objects library.
- Set frame for the ScrollView.
Now as we are set with the scrollview, we will add a content view to the UIScrollView. This content view will hold the elements of the ScrollView.
- Add another view to scroll view and keep the frame same as that of ScrollView.
Now we will add some auto layouts to the UIScrollView and the Content View.
we need some more constraints for the content view.
Give the content view as equal height and width constraints
Note: (Important Step) Now we will edit the height constant of the content view. Change the priority to low from high.
We are nearly done with the constraints of the ScrollView and the content view. Now we will add subviews to the content View.
Add as many as subviews to the content view. Here we will add an image view at the top. Some TextFields. a TextView a button.
Now we will add constraints to this components, and for segregation add a background color as well.
To all the components give 4 constraints: Top, leading, trading, fixed height constraint.
Now Select the last component, which is a UIButton. Add bottom constraint to the UIButton.
You will see after adding constraint value as “Bottom Space to: Superview Equals Some negative value”
We will now edit the value of the bottom constraint.
Edit the value of the bottom constraint.
Change the value of constant to >= (greater then or equals to) 8
This value 8 tells the final button to keep a bottom spacing of 8px from the scroll view.
We are all set to see the scroll view, run on any device and see the scrollview magic.
Hope this tutorial will be helpful for you. You can download the whole project from here.