How to use the new UIScrollView programmatically

Sheikhamais
3 min readMar 26, 2021

--

UIScrollView has been greatly improved by apple, with the introduction of new scrollView.contentLayoutGuide and scrollView.frameLayoutGuide.

Having difficulty understanding and using it — no worries. We will implement it in a simple way.

We will be making this in the end:

Lets get started

Consider the above image with scroll view having content way larger than the screen size. Now whenever using auto-layout while applying constraints, frame guide refers to size with respect to the screen and content guide refers to the size with respect to all the content inside scroll content view.

Done with the words. Let’s implement a simple scroll view with dynamic horizontal and vertical scrolling.

First of all declare the variables

I usually use a container view i.e. scrollContainer to add all the scroll view content inside this container.

Now add the scroll view to the view controllers view, and pin it

Now, your scroll view’s frame is equal to the view of viewController, i.e the screen size if it is a full screen view controller.

Here comes the magic constraints:

We will always pin the scrollContainer to the contentLayoutGuide of the scrollView in order to get all content covered.

Now pin the leading/trailing of scrollContainer to the frameLayoutGuide of scrollView, which we remember that the scrollView frame is now frame of view of viewController which is size of the screen. We are giving it a height of 1200 which is beyond the screen size, so that this container is now able to be scrolled vertically.

Similarly, pin top/bottom and give width, now whatever is inside scrollContainer is now able to be scrolled horizontally.

And both dimensions could be kept scrollable by giving large height/width values without pinning with the frame.

For dynamic height/width

Consider adding a label, and now you want the scroll view to fit the size of label.

Just add the label to the scrollContainer and apply the following constraints

This how, your scroll View now adapts the content inside a label and is now vertically scrollable. See this

You can use this technique to design any content and put inside a scroll view.

Have a good day :)

--

--

Sheikhamais
Sheikhamais

No responses yet