Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong trailing space constraints for children of UIScrollView

Tags:

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 scroll view would fill its parent completely.

Then I added a button as child of the scroll view, with space constraints of 15 to "Superview" (i.e. to the scroll view). I would thus expect the button to have a spacing of 15 to top/left/right borders, and the scroll view's content to end at 'bottom of button + 15'. However the width of the button is not correct (tested within Xcode 5 Interface Builder, iOS 6/7 simulators):

Example

It doesn't even work if I constrain the button with "Equal Width to Superview"! Still doesn't take up the full width.

How do I solve this?

like image 412
AndiDog Avatar asked Sep 23 '13 07:09

AndiDog


1 Answers

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.
like image 66
AndiDog Avatar answered Sep 21 '22 19:09

AndiDog