I was reading the description of viewDidLayoutSubviews
of UIViewController
:
Called to notify the view controller that its vi
viewDidLayoutSubviews
will be called when
When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method.
For example you have set constraints
of your view then you want to update the frame for your subview in viewDidLoad()
, which will not make any impact as in viewDidLoad()
your constraints
are not properly set, they will get properly set when viewDidLayoutSubviews
get called, now you want to update the frames of your subview, then you can do that in this method as this method get called only after all the constraints of your view are properly set.
When bounds change for a ViewControllers View, this method is called after the positions and sizes of the subviews have changed.
So this is our chance to make changes to view after it has laid out its subviews, but before it is visible on screen.
Any changes that depending on bounds has to be done, we can do here and not in ViewDidLoad or ViewWillAppear.
While ViewDidLoad & ViewWillAppear, the frame and bounds of a view are not finalised. So when AutoLayout has done it's job of fixing mainView and it's subviews, this method is called.
When using autolayout, framework does not call layoutSubviews every time. This is called in these cases.
Rotating a device: only calls layoutSubview on the parent view (the responding viewControllers primary view)
Its own bounds (not frame) changed. (The bounds are considered changed only if the new value is different, including a different origin.)
setNeedsLayout
or layoutIfNeeded
method of a view.Note: The call for viewDidLayoutSubviews also depends on various factors like autoresize mask, using Auto-Layout or not, and whether view is in view hierarchy or not.
For any other clarification, check When is layoutSubviews called?