What is the difference between setNeedsLayout, layoutIfNeeded and layoutSubviews? Quick Notes.

Screen Shot 2018-06-06 at 9.50.17 AM

When the user taps an on App icon, iOS creates an instance of UIApplication which runs on the main thread. This main thread processes all UI events such as touch, location updates etc.

After app launched successfully, it becomes available for the user to do interactions with it and every single interaction which known as an event is processed in a FIFO manner.

Now while events are being processed there may come some UI update requests which aren’t get fulfilled immediately. Instead, the system waits until the existing process finishes and the next redraw cycle comes. There is a periodic interval between the event processing and UI layout handling. The setLayoutNeeded() and layoutIfNeeded are two UIView’s methods here to ask the system for updating the view with new changes.

The setNeedsLayout() tells the system that you want the view and all it’s subviews to be redrawn in the update cycle.

Here is What Apple’s doc says on this, “Call this method on your application main thread when you want to adjust the layout of a view’s subviews. Note that it returns immediately (Async call) because it does not force an update, it waits for the next update cycle”.

Whereas layoutIfNeeded() is an async call which tells the system that you want the view and it’s subviews to be redrawn immediately without waiting for the next update cycle.

UIView have one more method named layoutSubviews() which you can use for your own implementation to set the frame of your view directly by overriding it. And since it’s default implementation uses the constraints you have given to determine it’s size and positions to get the frame, you should override it unless autoresizing and constraint behavior is not working for you as expected.

In short use setNeedsLayout(), if you are okay with the system to update it in the next upcoming update cycle and use layoutIfNeeded() if you want it to be updated immediately.

Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.