When and how is layoutIfNeeded used? I know that when we change the layout of a view, we can call setNeedsLayout to update the layout but not sure when layoutIfNeeded should be used.
NOTE: I have layoutIfNeeded used in actual code but forgot in what context it was used.
layoutIfNeededforces 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 calledsetNeedsLayoutwhen handling some user action). Then, your customlayoutSubviewsmethod will be called immediately instead of when it would normally be called in the regular UIKit run loop event sequence (after event handling, but beforedrawRect:).An example of why you might need to call
layoutIfNeededwithin a single run loop:setNeedsLayoutis set so thatlayoutSubviewswill be called later.layoutSubviewsthat 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
layoutSubviewsis done. A solution then would be for the controller to calllayoutIfNeededin situations where it knows this might occur.