Daniele B
Daniele B

Reputation: 20412

iOS: how to set constraints to UIScrollView

I would like to implement a simple UIViewController with vertically scrollable content.

I have been trying to use UIScrollView, but I am struggling with setting the constraints in Interface Builder. Can anyone illustrate the proper way to do it?

Let's consider a page which has a UILabel with a long text and a couple of UIImageViews placed at the bottom of the text.

Upvotes: 0

Views: 140

Answers (1)

seto nugroho
seto nugroho

Reputation: 1379

UIScrollView has 2 important properties when dealing with autolayout constraint and scrolling function. Those are size and content size.

UIScrollView size is the size of UIScrollView related to its superview. You can set its constraint by pin each of top, trailing, leading, bottom to its superview.

UIScrollView content size on the other hand is the size of UIScrollView subview related to it. It is basically the scrollable size. Setting the constraint of its subview is a little bit tricky, you can't just pin each side of each subview to UIScrollView. You also need to add some height and width constraint to it so it won't give ambiously constraint warning.

Let's say for example that you have one UILabel and one UIImageView below the label.

A simple way to create vertically scrollable content would be:

  1. set top, leading, trailing space constraint of UILabel to UIScrollView
  2. set UILabel height and width constraint
  3. connect height constraint to code so you can modify its value.
  4. set UIImageView top constraint to UILabel
  5. set UIIMageView trailing, leading and bottom space constraint to UIScrollView
  6. set UIImageView height and width constraint
  7. change UILabel height constraint based on the text and call layoutIfNeeded

Upvotes: 1

Related Questions