UIScrollView Content Layout Guide with Auto Layout in Interface Builder

--

I will try to keep this short enough.

With iOS11, Apple introduced Content Layout Guide for UIScrollView and I will show you how it’s used with a vertical UIScrollView example:

1- Add a UIScrollView and attach it to safe area. Don’t worry about the errors yet.

UIScrollView in its safe area

Content Layout Guides is checked by default.

2- You can add anything you like, as an example I am adding a UITextView into UIScrollView. I set its “Scrolling Enabled” property to false so UITextView can calculate its intrinsic content height and provide that info to UIScrollView automatically. You have errors, still don’t worry, I am on it.

UITextView inside UIScrollView

3- Now it’s time to feed UIScrollView. UIScrollView needs to know the scrollable content area. We will use “Content Layout Guide” to give this info to UIScrollView since “Content Layout Guide” relates to the size of the scrollable content area inside UIScrollView. Pin UITextView into “Content Layout Guide” edges with constant value “0” for each constraints:

UITextView pinned to Content Layout Guide

4- Since the UIScrollView will scroll vertically, we need to anchor the content’s width. “Frame Layout Guide” will help us doing that because it relates to position and size of the UIScrollView, relative to it’s parent’s space. So we can use width constraint of “Frame Layout Guide” and make it equal to our UITextView’s width and enjoy our vertically scrollable UIScrollView.

Vertically scrollable UIScrollView

--

--

No responses yet