In this article, we will read about the UIView Auto Layout Lifecycle.
We will discuss the steps a UIView undergoes before it is presented to a user.
So let’s start with the article.
Overview of UIView Auto Layout Lifecycle
Every UIView containing auto layout has 4 steps before presenting to the user.
- Initialization
- Update
- Layout
- Render
We will discuss each step of the lifecycle assuming you have basic knowledge of the Auto layout.
One thing to remember is that the above-stated steps may or may not present sequentially in the lifecycle of the UIView with auto layout.
The initialization step initializes the UIView, after that other steps are present.
Update
Calling updateConstraints() for each view manages the update step. This process happens automatically but sometimes we need to do this manually when we want to update the constraints after some event.
We use setNeedsUpdateConstraint() to invalidate the contraints.
After that, updateConstraintsIfNeeded() triggers updateConstraints() which updates the constraints.
Read what the official documentation says here.
Layout
We use layoutSubviews() when the constraints are not enough for the view layout.
Firstly, setNeedsLayout invalidates the view’s layout and then layoutIfNeeded() calls layoutSubviews() if the constraints are invalidated previously.
You must call the super.layoutSubviews() to layout the updated constraints, but try to avoid modifying the constraints outside the view.
Here is what Apple describes layoutSubview()
Render
Displaying the pixels on the screen is the major target of the render step.
In this step, it is not necessary that any view has an auto layout or not.
This step uses drawRect to display the UIView content.
You should never call this method directly yourself. Firstly, invalidate that part of your view and then call setNeedsDisplay.
Conclusion
This is just an overview of the lifecycle of the UIView with auto layout.
You can go through the official documentation here to dig out more.
Please visit my other blogs here.
Thanks for your reading.