How is layoutIfNeeded used?

Viewed 51657

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.

4 Answers

The difference between these two methods can be now be described by referencing the update cycle.

The method setNeedsLayout for a UIView tells the system that you want it to layout and redraw that view and all of its subviews, when it is time for the update cycle. This is an asynchronous activity, because the method completes and returns immediately, but it isn’t until some later time that the layout and redraw actually happens, and you don’t know when that update cycle will be.

In contrast, the method layoutIfNeeded is a synchronous call that tells the system you want a layout and redraw of a view and its subviews, and you want it done immediately without waiting for the update cycle. When the call to this method is complete, the layout has already been adjusted and drawn based on all changes that had been noted prior to the method call.

So, stated succinctly, layoutIfNeeded says update immediately please, whereas setNeedsLayout says please update but you can wait until the next update cycle.

LayoutSubViews() - Don’t call directly, instead call setNeedsLayout(),override if constraint base not offer expected behaviour.

SetNeedsLayout()- Call on main thread, it wait for next drawing cycle. good for performance.

LayoutIfNeeded() - Layout subviews immediately.

setNeedsLayout actually calls layoutIfNeeded, so if your calling setNeedsDisplay there's no reason to call layoutIfNeeded. In this way setNeedsLayout is a convenience method for calling layoutIfNeeded which does the heavy lifting.

Related