This time we are going to look into how to embed custom view in UIScrollView and setting up autolayout constraints for different scenarios.
Setting up view controller with scroll view
We’ll gonna create a new view controller what contains UIScrollView as it’s subview. UIScrollView will cover the whole view area. Everything is set up in code as it is easier to represent the steps needed. It is easy to use those steps and setting up constraints in interface builder.
Case 1: Vertically scrollable view
Most common case is to have scroll view with vertically scrollable content. Embedded view’s leading, trailing, top and bottom layout anchors should be equal to scroll view’s content layout margin’s corresponding anchors. For making the view only scrollable in vertical axis, embedded view’s width should match with scroll view’s width. This is achieved by adding an extra width constraint to the embedded view. Width constraint should make the view width equal to scroll view’s width. When setting view’s up in interface builder, make sure to add at least one subview to the embedded view what has intrinsic content size (label, button etc) (also add constraints). Otherwise interface builder does not know what size the embedded view has.
Case 2: Horizontally scrollable view
Horizontally scrollable view follows the same setup except instead of width constraint, we’ll add height constraint instead. When setting up the height constraint, scroll view’s safeAreaLayoutGuide’s heightAnchor should be used. This layout guide ignores the portion of the view what is covered by navigation bars, tab bars, toolbars, and other views.
Case 3: Vertically and horizontally scrollable view
For making the embedded view to be scrollable in horizontal and vertical axis, we’ll only add leading, trailing, top and bottom constraints to scroll view’s contentLayoutGuide’s corresponding anchors. Embedded view should define intrinsicContentSize as this size is used by scroll view for knowing what size the view wants to be. This kind of layout is probably usable only for fixed size view’s. For example, building a custom grid view where the row and column count define the size of the view.
We took a look on how to add constraints to embedded view in scroll view for getting a specific scrolling behaviour. In one sentence: leading, trailing, top, and bottom constraints to contentLayoutGuide and adding width or height constraint when necessary.
UIScrollViewExample (Xcode 11.0)