Autolayout & UIViews go hand-in-hand. When working with UIViews constraint with Autolayout, there are two functions that developers must know about. I have seen experienced developers not having much idea about how are these two different from each other. So today i will try to explain about these two functions and the scenario where they can be used.
The UIApplication starts the main run loop, on the main thread. The main run loop responds to the view based updates and events (like touch, system event, motion, etc). When an event happens, the main run loop finds the handler which will handle the event, and then calls consequent functions. When the handler handles the event, the control is returned to the main run loop. This is the time when the main run loop is now free to process the next events(queued events or view updates).
When the run loop is busy processing and dispatching events, if meanwhile, any view updates are requested, then they will not be executed right away. Instead, they will be recorded and will be executed in the next update cycle ( or when the event handler has returned the control to the main run loop). Since this is a very short interval, it is not noticed by the user, but this time interval in the update cycle is the difference between layoutIfNeeded() and setNeedsLayout().
The main difference comes when you are animating the views
The Layout process
There are three steps in the auto layout and views layout process:-
- Constraint pass : In this phase, Autolayout calculates the constraints for the resizing and positioning of the views on the screen.
- Layout pass: All the views and the subviews are laid out according to the constraints updated in the last phase (constraint phase).
- Render pass (Redraw) : Views are redrawn on the drawn using the drawRect() for the UIViews.
Whenever constraint pass occurs, layout pass will always occur next
Using setNeedsLayout sets the flag that the view is to be updated in the next update cycle. This is an asynchronous method. It completes and returns immediately. But effect will be seen in next update cycle during the layout and redraw phase(But we don’t know when the next update cycle will be).
While layoutIfNeeded forces the system to call layoutsubviews immediately. After that the control is returned back to the main run loop.
layoutIfNeeded() // Immediate (Update this f**king moment) setNeedsLayout() // Relax. I can wait for the next layout pass.
While encountering these methods for the first time, may deceive anyone. since layoutIfNeeded() can infer, as if it is less urgent. But intact, this is the opposite.
You can also refer to the diagram to better remember the order of these passes.
You can download an example visually showing the example between them on the GitHub.