According to the documentation for -[UIView setNeedsLayout]
:
Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.
Sounds great - but when I use setNeedsLayout
without then calling layoutIfNeeded
, I find that my control doesn't lay itself out. I had hoped that an "update cycle" would happen before the control was next shown, but I guess that isn't how it works. So what is an "update cycle"? When does one happen?
Steps overview. Every UIView with enabled Auto Layout passes 3 steps after initialization: update, layout and render. These steps do not occur in a one-way direction. It's possible for a step to trigger any previous one or even force the whole cycle to repeat.
If you want to force a layout update, call the setNeedsLayout() method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded() method.
The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.
Layout PassThe system traverses the view hierarchy again and calls viewWillLayoutSubviews on all view controllers, and layoutSubviews ( layout in OS X) on all views. By default, the layoutSubviews method updates the frame of each subview with the rectangle calculated by the Auto Layout engine.
The 'update cycle' happens at the end of the current run loop cycle.
setNeedsLayout
must be called on the main thread (main runloop).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With