iOS swift — setNeedsLayout vs layoutIfNeeded vs layoutSubviews()

I always wondered about these methods while coding in iOS. I tried to read more and this is what I understood.

When an iOS app launches, UIApplication in iOS starts the main run loop for an app, which runs on the main thread. The main run loop processes events (such as user touches) and handles updates to view-based interfaces. As events occur, such as touch, location updates, motion, and multimedia control, the run loop finds the appropriate handler for the events, calling appropriate methods, which call other methods, and so on. At some moment in time, all events will have been handled and control will return to the run loop. Let’s label this point where control is returned to the run loop as the update cycle.

While the events are being processed, and some changes are requested to the view, these changes are not updated immediately. Instead the system wait for the existing process to finish and when the next redraw cycle is going to happen. There is a periodic interval between the event processing and UI layout update handling. This is why we need to understand the above three methods properly.

— setNeedsLayout()

Apple doc says: Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. 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.

— layoutIfNeeded()

— layoutSubviews()

The default implementation uses any constraints you have set to determine the size and position of any subviews.

Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.

You should not call this method directly. 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.

For a better understanding , download and run the code in Github. I found this from the link mentioned below.

Source: Link1 , apple docs.

iOS and tvOS developer, dreamer, photographer 🤨

iOS and tvOS developer, dreamer, photographer 🤨