When do the ViewWillLayoutSubviews
and ViewDidLayoutSubviews
methods of UIViewController get called? What is the status of the view's frame before willLayoutSubviews
?
viewWillLayoutSubviews() Called to notify the view controller that its view is about to layout its subviews.
Meaning the method viewDidLayoutSubviews is called every time the view size changes and the view layout has been recalculated.
viewWillLayoutSubviews gets called anytime your view controller's view has its bounds changed. This happens when the view is loaded, when a rotation event occurs, or when a child view controller has its size changed by its parent.
From the documentation:
When a view's bounds change, the view adjusts the position of its subviews. Your view controller can override this method to make changes before the view lays out its subviews. The default implementation of this method does nothing.
viewWillLayoutSubviews
gets called anytime your view controller's view has its bounds changed. This happens when the view is loaded, when a rotation event occurs, or when a child view controller has its size changed by its parent. (There are probably some other situations, too). If there is anything you need to update before that view lays itself out (and before your constraints are re-applied) you should do it here. you should generally not update constraints here, because updating constraints can cause another layout pass.
viewDidLayoutSubviews
is called once all of your subviews have been laid out. If you need to fine-tune that layout by manually adjusting frames, for instance, this would be the place to do it.
View controller lifecycle can be a bit confusing, but it's worth trying to really understand if you're going to be doing much iOS development. This article is a really good overview.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With