Search code examples
iosobjective-cuiviewuiscrollviewcontentsize

Why my UIView inside UIScrollView doesn't respect its height contraint?


I would like to make a simple UIScrollView. For that I put an UIView inside it, and put all my components inside this UIView.

enter image description here

My problem is that I programmatically set the contentSize of my UIScrollView (and it works perfectly), but my UIView doesn't respect this new height... So my components in the bottom are not in my UIView but in my UIScrollView !

enter image description here

This is a problem because my UISegmentedControl ("Consommation/Emission") doesn't respond, contrary to the test UISegmentedControl ("First/Second") which works.

I put an equal height constraint between the UIScrollView and the UIView but it doesn't work...


Solution

  • The equal height constraint will make the frames the same size but will not cause the height of the view to equal the content size. I would create an actual height constraint for the view then make IBOutlet of that constraint and update it's constant when you set the scrollview's contentSize.height something like

    self.viewHeightConstraint.constant = self.scrollView.contentSize.height;
    

    wherever you're updating you scrollview's content size. I would say, when using auto layout, it's generally better to set or update constraints than setting frames. Setting frames tend to fight with the layout engine.

    enter image description here

    Find the constraint you set by checking the "Equal Heights" box. Check the "Height" box create an IBOutlet to that.