How can I use Autolayout to set constraints on my UIScrollview?

后端 未结 18 1658
别那么骄傲
别那么骄傲 2020-11-28 00:43

I have spent two days trying out the various solutions for Mixed and Pure Autolayout approaches to achieve what was a trivial scrollview setup prior to autolayout, and it\'s

18条回答
  •  温柔的废话
    2020-11-28 01:33

    There are so many questions about using AutoLayout with UIScrollView, the key point which we ignore is that the inner views of the UIScrollView make constraints against the Content View but not the UIScrollView itself. Refer to the Technical Note TN2154, you can find:

    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 following figure will depicts that: enter image description here

    You can find the trailing space is 500 points, if the constraint is made to the UIScrollView, the view will be miss placed and should be update its frame. However, no warnings and no errors. Because all the constraints are against the content view.

    UIScrollView will calculate the size of the content view according to the constraints of the inner views. (For the example, the content size: width = 100(leading space) + 200 (view's width) + 500 (trailing space), height = 131 (top spacing) + 200(height) + 269(bottom spacing)

    How to add constraints for views in the UIScrollView:

    1. Imaging the positions of views in the content view.
    2. Add top, right, bottom, left spacing to the edges of the content view, in addition, also the width and height of these views.

    And all it is done.

    An easy way to deal with AutoLayout with scrollview is to add a container view containing all subviews in the scroll view.

    Conclusion: the key point to understand AutoLayout with UIScrollView is inner views make constraints against the content view but not UIScrollView itself.

    attached example code

提交回复
热议问题