Haravikk
Haravikk

Reputation: 3280

Fill Vertical Space of UIScrollView

I'm working on a layout that has a UIScrollView, and what I want to do is have a label pinned to the top of the scrollable area, and a button pinned to the bottom, with a minimum amount of space between the two.

The idea is that if the label grows in height the button will be pushed downwards so that the user has to scroll down to get to it. However, if the label is short, the space between it and the button should grow so that the button stays at the bottom of the scrollable area.

Below is a rough mockup of what I mean:

enter image description here

NOTE: The second shot is after scrolling all the way to the bottom of the UIScrollView, I want the button to be hidden when scrolled to the top; i.e- simply placing the button below the scroll view is not an option.

Upvotes: 5

Views: 1966

Answers (1)

Kévin
Kévin

Reputation: 890

You can achieve the desired result with autolayout only, without having to change constraints via code. The steps are as follows:

1) Create your scrollview and pin it to all sides: enter image description here

2) Add a view, which will act as content view, to the scrollview and pin it as well: enter image description here

3) Your label and button will be added to this contentView, but before we can do this, we must add 2 additional constraints to the contentView. Create constraints for the width and height of the contentView to be equal as the SafeArea. You should set the priority of the equal heights constraint to low (250): enter image description here

4) Add your label and button inside the contentView. The label pinned to the top and the button pinned to the bottom;

5) Lastly, add a vertical spacing constraint between the label and the button. Set the desired minimum amount of space between the button and the label as this constraint's constant, for instance 8, and set the relation to be Greater Than or Equal: enter image description here

With this, if the label grows in height, the button will be pushed downwards so that the user has to scroll down to get to it.

enter image description here

Upvotes: 15

Related Questions