iosswiftuser-interfaceuiscrollviewautolayout

Using Scroll View with Autolayout Swift


I know this question has been asked many times but this is a problem I have been struggling with for a long time and I'm sure others are too, even with the current answers and tutorials out there.

When adding a Scroll View I go through the following steps:

  1. Add a Scroll View as a subview of the original view in the view controller. Pin top, left, right, and bottom. Ensuring that "Constrain to margins" is unchecked.

  2. Add a UIView as a subview of the Scroll View. Pin top, left, right, and bottom constraints.

  3. Add an equal widths constraint between the content view and the view controllers view.

At this point of I run the app the content view does not appear and the scroll View takes up the entire screen.

  1. Next I add elements to the Content View that just include 4 UIViews to test everything. I give each UIView top, left, and right constraints. And the last UIView a bottom constraint.

Not at this point when I run the app the Content View and Scroll View each take up about half of the screen and I can scroll the Content View around. See below photo.

I have followed every tutorial I can find and tried implementing all SO answers I have found but I can't seem to get it to work. If anybody has come across this or knows a solution your help would be very much appreciated!

The green is the Content View and the blue is the Scroll View

enter image description here

Scroll View and Subview constraints

enter image description here


Solution

  • 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.