UIScrollView that expands with contents' instrinsic size until height X, and then scrolls

I think I have achieved an effect similar to the one you wanted with pure Auto Layout.

THE STRUCTURE

First, let me show you my structure:

enter image description here

Content View is the view that has the white background, Caller View and Bottom View have a fixed height. Bottom View has your button, Caller View has your title.

THE SOLUTION

So, after setting the basic constraints (note that the view inside scroll view has top, left, right and bottom to the scroll view AND an equal width) the problem is that the scroll view doesn't know what size should have. So here comes what I have done:

I wanted that the scroll could grow until a max. So I added a proportional height to the superview that sets that max:

enter image description here

However, this brings two problems: Scroll View still doesn't know what height should have and now you can resize and the scroll view will pass the size of his content (if the content is smaller than the max size).

So, to solve both issues I have added an equal height with a smaller priority from the View inside of the Scroll View and the Scroll View

enter image description here

I hope this can help you out.


Your problem can't be solved with constraints alone, you have to use some code. That's because the scroll view doesn't have an intrinsic content size.

So, create a subclass of scroll view. Maybe give it a property or a delegate or something to tell it what its maximum height should be.

In the subclass, invalidate the intrinsic content size whenever the content size changes, and calculate the new intrinsic size as the minimum of the content size and the maximum allowed size.

Once the scroll view has an intrinsic size your constraints between it and its super view will actually do something meaningful for your problem.


It can be done in Interface builder using auto layout without any difficulties.

  1. set outer container view ("Parent container for scrollview" in your sample) height constraint with "less than or equal" relation.

2.add "equal heights" constraint to content view and scroll view. Then set low priority for this constraint.

That's all. Now your scrollview will be resized by height if content height changed, but only to max height limited by outer view height constraint.

enter image description here enter image description here enter image description here