resize superview after subviews change dynamically using autolayout

Pedroinpeace picture Pedroinpeace · Oct 4, 2013 · Viewed 75.8k times · Source

I cant for the love of god the the hang of this resizing superview.

I have a UIView *superview with 4 UILabels. 2 function as header for the 2 others.

The content in all 4 are dynamic coming from database.

SizeToFit vs SizeThatFits:(CGSize) vs UIView systemLayoutSizeFittingSize:, passing either UILayoutFittingCompressedSize or UILayoutFittingExpandedSize.

I use autolayout programatically and have set the superview height to be equal or greater to a dummy number.

where and how do I use these SizeToFit vs sizeThatFits:(CGSize) vs UIView systemLayoutSizeFittingSize:, passing either UILayoutFittingCompressedSize or UILayoutFittingExpandedSize. I have read a lot of tips here on stack but ended up with nothing.

DO I need to recalculate the constraints for the superview somewhere specific. Maby setting the height to be ´@property` in its controller class and remove and readd it? Atm I have tried to put everything everywhere and then some. Still I get the same size end result with the dummy height and text floating outside. Even after setting clipsToBound on subview.

I am scratching my hair of.. help

Answer

smileyborg picture smileyborg · Oct 5, 2013

If you're using Auto Layout, here's what you need to do:

  1. Make sure you aren't adding fixed width and/or height constraints to any of your subviews (depending on which dimension(s) you want to dynamically size). The idea is to let the intrinsic content size of each subview determine the subview's height. UILabels come with 4 automatic implicit constraints which will (with less than Required priority) attempt to keep the label's frame at the exact size required to fit all the text inside.

  2. Make sure that the edges of each label are connected rigidly (with Required priority constraints) to the edges of each other and their superview. You want to make sure that if you imagine one of the labels growing in size, this would force the other labels to make room for it and most importantly force the superview to expand as well.

  3. Only add constraints to the superview to set its position, not size (at least, not for the dimension(s) you want it to size dynamically). Remember that if you set the internal constraints up correctly, its size will be determined by the sizes of all the subviews, since its edges are connected to theirs in some fashion.

That's it. You don't need to call sizeToFit or systemLayoutSizeFittingSize: to get this to work, just load your views and set the text and that should be it. The system layout engine will do the calculations for you to solve your constraints. (If anything, you might need to call setNeedsLayout on the superview...but this shouldn't be required.)