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

Suragch picture Suragch · Jun 18, 2016 · Viewed 7.6k times · Source

I'm basically trying to reproduce the behavior of the title and message section of an alert.

enter image description here

The title and message labels appear to be in a scroll view. If the label text increases then the alert height also increases along with the intrinsic content size of the labels. But at a certain height, the alert height stops increasing and the title and message text become scrollable.

What I have read:

Articles

Stack Overflow

The answer may be in there but I was not able to abstract it.

What I have tried:

Only focusing on the scroll view with the two labels I tried to make a minimal example in which a parent view would resize according to the intrinsic height of the scrollview. I've played around with a lot of constraints. Here is one combo (among many) that doesn't work:

enter image description here

I've worked with auto layout and normal constraints and even intrinsic content sizes. Also, I do know how to get a basic scroll view working with auto layout. However, I've never done anything with priorities and content hugging and compression resistance. From the reading I've done, I have a superficial understanding of their meanings, but I am at a loss of how to apply them in this instance. My guess is I need to do something with content hugging and priorities.

Answer

Tiago Almeida picture Tiago Almeida · Sep 15, 2016

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.