Since I’ve just (hopefully) fully understood how on Earth the UIView layout mecanism works, I thaught I needed a note to re-read it as soon as I forget it!
The problem
Being able to call UIView’s -(void)sizeToFit to automagically layout a complex view tree like this one:
If you want this to be as simple as possible, you’ll need to call -(void)sizeToFit from the top level view (the blue one) – which will then call -(void)sizeToFit on the whole hierarchy (green, then yellow). I was stuck at first because I didn’t read carefully the Apple documentation for -(void)sizeToFit:
Resizes and moves the receiver view so it just encloses its subviews.
This means that we have a logical issue: we can’t call -(void)sizeToFit from top to bottom. If in the previous image, you take the 2nd green view which has two subviews that are not equals in height, you can’t determine the 2nd green view height without knowing the height used by its 2 children (the 2 yellow ones). And of course you can’t guess either the blue one’s height without knowing the 3 green height.
Summarized as:
If you want to lay out a parent view, you first need to lay out its children.
Methods we need to understand
UIView provides all the necessary methods to achieve this:
- - (CGSize)sizeThatFits:(CGSize)size
- - (void)sizeToFit
- - (void)layoutSubviews
- - (void)layoutIfNeeded
- - (void)setNeedsLayout
I had a hard time to figure out in which order I needed to call all these methods. Read carefully the code above, I’ve commented heavily so that you understand what it does. Right after, comes a schema which I hope is more meaningful.
I made the following schema to stick my mind on it. I hope I have a well understanding of what’s going on under the hood.
So now you can call -(void)sizeToFit from your top level view ; it will go straight to the deepest level and lay out all the views from bottom to top.
Hope this helps!
출처 : http://eddykudo.com/188