How to use UIScrollView on Auto Layout

I think UIScrollView is one of the component in iOS that most used by the developers other than UITableView. With Auto Layout around, we are now not able to use contentSize anymore, since the Auto layout taking care of all the sizes.

This is the simple thing on how to use UIScrollView on Storyboard with Auto Layout enabled. Please follow along the list below.

  • UIScrollView could be using full screen or any screen. The image below showing the top, leading, bottom, and trailing constraint is using full screen.
UIScrollViewConstraint
  • Add UIView as subview of the UIScrollView, and add the constraint as below image:
  • And this is the first trick. Select the UIScrollView and UIView, set the width and height of UIView to be the same as UIScrollView. See the image below.
Set width and height
  • And this is the second trick. If you wanted to have a horizontal scroll, set the width as low priority. Or, set the height as low priority if you want the scroll top and down. See below image.
Low priority on height
  • Time to add the content. You may put label, UIView, or anything you want under the UIView. We will add a orange box with height more than the screen to see the scrolling. Do not forget to set the top and bottom constraint of the orange box. In the image below, the orange box has height of 1760, width 240, align center X to superview, top and bottom constraint is 87.
  • Done. Please make sure the layout of your UIScrollView is on the image below. The UIView as Container to hold of your contents.
Layout
Show Comments