Using Scroll View with Autolayout Swift

I figured this out with the help of the other answers but I had to make some adjustments to get it work the way I wanted. Here are the steps I took:

  1. Add a Scroll View as a Sub View of the Main View.

  2. Select the Scroll View and uncheck "Constrain to margins" and pin top, left, right, bottom, constraints

  3. Add a UIView as a subview of the Scroll View. Name this view "Content View"

  4. Select the Content View and pin top, left, right, and bottom constraints. Then add a center horizontally constraint.

  5. Next from the Content View to the Main View add equal width and equal height constraints.

  6. Add whatever elements you need inside the Content View. Pin top, left, right, and height constraints to the elements that were just added.

  7. On the bottom most item inside the Content View pin a bottom constraint. Select this constraint and change to "Greater Than or Equal". Change the constant to 20.

The constraints added to the items inside the Content View are very important, especially the bottom constraint added to the last item. They help to determine the content size of the scroll view. Adding the bottom constrain as I described will enable the view to scroll if the content is too large to fit in the screen, and disable scrolling if the content does fit in the screen.


Xcode 11 Swift 5

More info here

In order for scrollview to work in Auto Layout, scrollview must know its scrollable content (scrollview content) width and height , and also the frame (X, Y , Width, Height) of itself, ie. where should the superview place scrollview and what size.

With Xcode 11 two new things Content Layout guide and Frame Layout guide were introduced in Interface Builder.

Now for making work scrollView from storyboard you should:

  • Put a scroll view into the view controller and set constraints (leading, top, trailing, bottom - all 0)
  • Put a view(contentView) inside the scroll view and set constraints (leading, top, trailing, bottom - all 0)
  • In views hierarchy, do ctrl drag from new View(contentView) to Content Layout guide of scrollView and in the appeared context menu choose all constraints (leading, top, trailing, bottom - all 0)
  • If we want to make the scrollview scroll only vertically, create an equal width constraint between the view and the scrollview's Frame Layout guide (for horizontally create equal height constraint)
  • Place all your content view elements inside it and create all vertical constraints in the way that the top and the bottom of the contentView must be connected by constraints inside it.

That's it