Wrong trailing space constraints for children of UIScrollView

后端 未结 1 1912
名媛妹妹
名媛妹妹 2020-12-23 21:46

I have created a fresh View Controller, then added a Scroll View as child of the root View, and set \"Leading/Top/Trailing/Bottom Space to Superview\" to 0 so that the scrol

相关标签:
1条回答
  • 2020-12-23 22:21

    Found a good solution :) The reason for this behavior is that the scroll view adapts its content view size to what is actually needed by its subviews, and won't fill width/height automatically. If width should be filled, the scroll view thus must contain at least one view that fills the width of the screen.

    With these steps, I added a view that has equal width to the scroll view (the scroll view itself, not its content view area), leading to my scroll view finally expanding to the full width because I had also added constraints "space to superview 0/0/0/0" to the scroll view.

    • Assuming an empty view controller with one root view
    • Add scroll view, set constraints "space to superview top/left/right/bottom=0/0/0/0" on it
    • Add your UI to the scroll view however you want and set constraints also how you want
    • Add a new View, rename it to something like "Ensures scroll view fills width", with the following constraints
      • Leading/trailing/top space to superview (that's the scroll view!) = 0
      • Height 0 because we want it to be invisible because the view is only a helper
      • Important part: Select this view and the scroll view in the hierarchy and constrain them to equal width. Since the scroll view is constrained to its superview, it will receive a width. Then this constraint ensures that the scroll view's content view is also (at least) that wide.
    0 讨论(0)
提交回复
热议问题