UIScrollView Scrollable Content Size Ambiguity
Xcode 11+
The simplest way using autolayout
:
- Add
UIScrollView
and pin it0,0,0,0
to superview (or your desired size) - Add container of
UIView
type inside ScrollView, pin it0,0,0,0
to all 4 sides and center ithorizontally
andvertically
. - In size inspector of container, change
bottom
andalign center Y
priority to 250. (for horizontal scroll changetrailing
andalign center X
) - Add all views that you need into said container (UIView). Don't forget to set the bottom constraint on the lowest view.
- Select the
UIScrollView
, select the size inspector and deselectContent 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
but like this - to Content Layout Guide.
And then the most of the answers will work for you.
The most simple approach now is going like this:
- Put scroll view in the root view
- Pin all the sides of scroll view to the superview
- Take another UIView (will call it content view) and put it inside the scroll view
- Pin all the sides of the content view to scroll view's Content Layout Guide
- Pin the content view's width to be equal to scroll view's Frame Layout Guide
- 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
Updated
Nowadays, Apple realized the problem we solved many years ago (lol_face) and provides Content Layout Guide and Frame Layout Guide as part of the UIScrollView
. Therefore you need to go through the following steps:
Same as original response below;
For this
contentView
, set top, bottom, left, and right margins to 0 pinning them to the Content Layout Guide of the scroll view;Now set the
contentView
's height equal to the Frame Layout Guide's height. Do the same for the width;Finally, set the priority of the equal height constraints to 250 (if you need the view to scroll vertically, the width to scroll horizzontally).
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
.
Don't forget to set the constraint from the bottom of the last object in your contentView
to the contentView
's margin.
Original [Deprecated]
So I just sorted out in this way:Inside the
UIScrollView
add aUIView
(we can call thatcontentView
);In this
contentView
, set top, bottom, left and right margins to 0 (of course from thescrollView
which is thesuperView
); Set also align center horizontally and vertically;