Friday 21 November 2014

UIScrollView with Autolayout

This is my second post in iOS tutorial series.

Yesterday I have to deal with UIScrollView in Autolayout, but I didn't found any good tutorial who will teach this, so I decided to write this tutorial.

Earlier without Autolayout, if UIscrollview contains controls with height more than UIScrollView then we have to set UIScrollview's contentSize to scroll the UIscrollView.

But in autolayout mode even if we set its contentSize the UIscrollView will not scroll. In Autolayout mode we don't have to set contentSize of UIScrollView and adopt a new way, so it will scroll without much effort.

Enough talking, now we will start the tutorial. In this tutorial all we have to do is with Storyboard and no code. :)

1) Let's create one project with Single View Application, save it in desired directory.



2) Now we have one view controller, let's add one UIScrollView from Object Library to the view present in view controller. The UIScrollView should fill whole view as shown in below figure.



3) Now we have to add constraints for this UIScrollView, click Pin and add top, left, right and bottom constraints as shown in below diagram.



4) This part is very important for scrolling of UIScrollView. Now we have to  add UIView inside UIScrollview. This view will act as container of other controls, and we will increase its height to add other controls. So let's add UIView inside UIScrollView.



5) Increase this latest UIView's height, I am increasing to 800.



6) Now add your controls wherever you want.

7) Now we have add constraints to UIView, click on Pin and set constraint for top, left, right, bottom, width and height.



8) Now we have to change Bottom space constraint of scrollview's descendant view. Change its negative value to 0 as shown in figure.





9) Now run your program and happy scrolling. This project is added on Github here



No comments:

Post a Comment