Recently I read an interesting article on making
UIScrollView work with iOS
Autolayout. It's quite pain to do it in the
Storyboard/Xib files. So I created a reusable library which could be easily used in any project. (And I am using in several side projects). This is so easy and simplified as making
UIScrollView work with
Autolayout has always been bit a pain to do each time.
I am also using TPKeyboardAvoiding library to avoid input fields being eclipsed by the keyboard. Code is pretty straightforward and is mostly inspired from above mentioned blog post.
First off initialize
ScrollViewAutolayoutCreator as follows,
ScrollViewAutolayoutCreator* autoLayoutScrollView = [[ScrollViewAutolayoutCreator alloc] initWithSuperView:[superView] andHorizontalScrollingEnabled:[horizontalScrollingEnabled]];
Where `superView` : The parent view to which you want to add `Autolayout` equipped `UIScrollView`
horizontalScrollingEnabled : Specify if
UIScrollView should support horizontal scrolling for its content or not
Once 'ScrollViewAutolayoutCreator' is instantiated, get hold of
contentView property of
ScrollViewAutolayoutCreator object. This is the actual view where we are going to add our subviews to
You can add as many views as possible to
contentView with required constraints.
However, as UIScrollView demands, the bottom most view must be constrained to the bottom of parent view. In this case
contentView. Which must be constrained to the
contentView bottom for
UIScrollView to work.
It can easily be done with library provided method as follows,
[autoLayoutScrollView addBottomSpaceConstraintToLastView:[bottomMostContentView] withBottomPadding:[bottomPadding]];
bottomMostContentView - Bottom most view added to
contentView (which must be constrained to superview bottom)
bottomPadding - Padding to the last view from bottom of the parent.
Instead of calling this method directly, you can also add required bottom space constraints manually using regular or visual constraints.
This library is hosted on Github Here. A demo example is provided in the library for easier reference.
Again thanks to Mike Woelmer for such an informative blog post.