layoutIfNeeded
forces the receiver to layout its subviews immediately if required.
Suppose you have overridden layoutSubviews
, and UIKit feels that your view requires layout for whatever reason (e.g. you called setNeedsLayout
when handling some user action). Then, your custom layoutSubviews
method will be called immediately instead of when it would normally be called in the regular UIKit run loop event sequence (after event handling, but before drawRect:
).
An example of why you might need to call layoutIfNeeded
within a single run loop:
- You resize a custom view containing a table view with a custom layout.
setNeedsLayout
is set so that layoutSubviews
will be called later.
- A controller object asks the table view to scroll to some particular cell when handling a user event.
- Your custom view performs some custom sizing of the table view in
layoutSubviews
that changes the table view size.
The problem is when the controller asked the table view to scroll (step 2), the table view had bounds that were stale. The updated bounds would only be set on the table view later (step 3). What the controller wanted the table view to scroll to may not actually be visible after layoutSubviews
is done. A solution then would be for the controller to call layoutIfNeeded
in situations where it knows this might occur.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…