UIScrollView Scrollable Content Size Ambiguity UIScrollView Scrollable Content Size Ambiguity ios ios

UIScrollView Scrollable Content Size Ambiguity


So I just sorted out in this way:

  1. Inside the UIScrollView add a UIView (we can call that contentView);

  2. In this contentView, set top, bottom, left and right margins to 0 (of course from the scrollView which is the superView); Set also align center horizontally and vertically;

Finished.

Now you can add all your views in that contentView, and the contentSize of the scrollView will be automatically resized according with the contentView.

Update:

Some special case is covered by this video posted by @Sergio in the comments below.


Xcode 11+

The simplest way using autolayout:

  1. Add UIScrollView and pin it 0,0,0,0 to superview (or your desired size)
  2. Add UIView in ScrollView, pin it 0,0,0,0 to all 4 sides and center it horizontally and vertically.
  3. In size inspector, change bottom and align center Y priority to 250. (for horizontal scroll change trailing and align center X)
  4. Add all views that you need into this view. Don't forget to set the bottom constraint on the lowest view.
  5. Select the UIScrollView, select the size inspector and deselect Content Layout Guides.


Xcode 11+, Swift 5

If you are wondering why all of the answers does not work anymore, make sure that you have pinned the content view (the one you've put inside the scroll view) to Content Layout Guide of the scroll view and NOT to Frame Layout Guide.

Content view edges (leading, trailing, top, bottom) should not be pinned like leading on the image - to Frame Layout Guide

Not like this

but like this - to Content Layout Guide.

Select Content Layout Guide from dropdown

enter image description here

And then the most of the answers will work for you.

The most simple approach now is going like this:

  1. Put scroll view in the root view
  2. Pin all the sides of scroll view to the superview
  3. Take another UIView (will call it content view) and put it inside the scroll view
  4. Pin all the sides of the content view to scroll view's Content Layout Guide
  5. Pin the content view's width to be equal to scroll view's Frame Layout Guide
  6. Fix the content view height in any way you want (I used just constant height constraint in the example below)

Overall your structure in the simplest implementation will look like this

enter image description here