Can anyone give a definitive explanation on the relationship between UIView's setNeedsLayout, layoutIfNeeded and layoutSubviews methods? And an example implementation where all three would be used. Thanks.
What gets me confused is that if I send my custom view a setNeedsLayout message the very next thing it invokes after this method is layoutSubviews, skipping right over layoutIfNeeded. From the docs I would expect the flow to be setNeedsLayout > causes layoutIfNeeded to be called > causes layoutSubviews to be called.
I’m still trying to figure this out myself, so take this with some skepticism and forgive me if it contains errors.
setNeedsLayoutis an easy one: it just sets a flag somewhere in the UIView that marks it as needing layout. That will forcelayoutSubviewsto be called on the view before the next redraw happens. Note that in many cases you don’t need to call this explicitly, because of theautoresizesSubviewsproperty. If that’s set (which it is by default) then any change to a view’s frame will cause the view to lay out its subviews.layoutSubviewsis the method in which you do all the interesting stuff. It’s the equivalent ofdrawRectfor layout, if you will. A trivial example might be:AFAIK
layoutIfNeededisn’t generally meant to be overridden in your subclass. It’s a method that you’re meant to call when you want a view to be laid out right now. Apple’s implementation might look something like this:You would call
layoutIfNeededon a view to force it (and its superviews as necessary) to be laid out immediately.