Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are the ViewWillLayoutSubviews and ViewDidLayoutSubviews methods called?

When do the ViewWillLayoutSubviews and ViewDidLayoutSubviews methods of UIViewController get called? What is the status of the view's frame before willLayoutSubviews?

like image 879
Waseem05 Avatar asked May 04 '14 14:05

Waseem05


People also ask

When viewWillLayoutSubviews is called?

viewWillLayoutSubviews() Called to notify the view controller that its view is about to layout its subviews.

How often is viewDidLayoutSubviews called?

Meaning the method viewDidLayoutSubviews is called every time the view size changes and the view layout has been recalculated.

When to use viewWillLayoutSubviews?

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.


1 Answers

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.

like image 75
cmyr Avatar answered Sep 30 '22 14:09

cmyr