Search code examples
iosobjective-cuiscrollviewautolayoutresize

Make UIScrollView with dynamic height subviews work automatically with Auto Layout


I have the following view structure with its constraints:

UIView "parent"
   UIScrollView (leading, trailing, top and bottom to superview)
      - UIView "container" (leading, trailing, top and bottom to UIScrollView, 
                            equal width and height so parent UIView)
         - UIView "A" (leading, trailing, top to UIScrollView, height of 200)
         - UIView "B" (top, leading and trailing to UIView A, height of 140)
         - UIView "C" (top, leading and trailing to UIView B, height >= 88 "rest
                       of the screen until bottom", bottom to UIView "container")

"A" and "B" UIView's do not change its size but "C" does. Inside it, I am adding programmatically n "labels containers" UIView that have different heights depending on the content of m UILabel that they host.

Right now, I am calculating the size of the n UILabel with boundingRectWithSize: and I am sizing the height of their parent "labels containers" UIView that it is being added inside "C" UIView setting its height constraint to the sum of all UILabel.

Then, I resize "C" UIView height constraint so that it is equal to the sum of all added UIView.

This is working perfectly on all different screen sizes, portrait and landscape. The UIScrollView is showing all three "A", "B" and "C" subviews, having "C" n UIView that host m UILabel.

But now I am having troubles when rotating the device. I face the problem that I have to recalculate the size of all UILabel to change the height constraint of all the "labels container" UIView and change the "C" UIView height constraint so that it can fit everything without large blank spaces between all views.

So my question is: how can I achieve the same behaviour using exclusively Auto Layout?

Now I have to recalculate sizes and change height constraints so that everything adapts, but I would love that all UILabel resize themselves automatically and fit their content, then the "labels container" UIView resize to fit all the UILabel and then "C" UIView resizes automatically to fit the content.

Thank you in advance!


Solution

  • Ok, I was doing three things wrong:

    1st: I was calculating the height of the labels to set then the size of the "labels container" UIView using a height constraint. Height constraints not needed as Auto Layout manages everything.

    2nd: I was modifying the "C" UIView constraint height manually by adding the height value of each "labels container" UIView added.

    3rd: After fixing the first two steps, I forgot to set the last added UIView constraint with its parent view...

    Now everything works as expected.