UIScrollView with Adaptive Layout

708 views Asked by At

I have a UIScrollView inside a UIView and another UIView (the container view) inside the scroll view. Before adaptive layout I pinned the scroll view to fit the external view and set the width and height of the container view (that was pinned to the scroll view too). In this way I could vertically scroll the view.

enter image description here

Now, with adaptive layout, I can't set width because of different screen sizes... which constraint do I have to set up? The only solution I could think was to set width programmatically to the screen size...

2

There are 2 answers

0
NRitH On BEST ANSWER

Constrain the container view's width to be equal to the root-level view's width. Remove the container view's hard-coded width constraint.

0
Aaron Brager On

From UIScrollView and Autolayout:

The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom, and right edges within a scroll view now mean the edges of its content view.

The constraints on the subviews of the scroll view must result in a size to fill, which is then interpreted as the content size of the scroll view. (This should not be confused with the intrinsicContentSize method used for Auto Layout.) To size the scroll view’s frame with Auto Layout, constraints must either be explicit regarding the width and height of the scroll view, or the edges of the scroll view must be tied to views outside of its subtree.

In your case, "Container View" must have a non-ambiguous size, independent from the size of the scroll view. The simplest way to do this is to add height and width constraints with their constant property set to the value you want.

So, if you want "Container View" to be the width of the screen, add a width constraint and set its constant to the current screen width at runtime.