Can you give an example of using code inside viewWillLayoutSubviews or viewDidLayoutSubviews?

As I understood from the documentation, inside LayoutSubviews (to the beginning of work? To the end?) Frames have real sizes (through restrictions) and you can change them.

But I could not find a normal example.

  • It is better to describe the problem you are trying to solve. I use this method when creating a cornerRadius in a dynamic UIView. So how constraints are already spelled out. - Victor Mishustin
  • @ViktorMishustin At the interview they asked me to tell in detail about LayoutSubviews and give an example of its use. I searched for a long time, but did not find anything intelligible and clear. - Ivan Kramarchuk

2 answers 2

Everything turned out to be quite simple.

The order of the UIViewController life cycle method calls is as follows:

  1. viewDidLoad
  2. viewWillAppear
  3. viewWillLayoutSubviews
  4. viewDidLayoutSubviews
  5. viewDidAppear

Moreover, when we call viewWillLayoutSubviews, we still do not have real frame coordinates / sizes, considering constraints, and in viewDidLayoutSubviews we already have real coordinates, and we can easily change them there.

If we change the coordinates / sizes in viewDidAppear, where we already have real coordinates / sizes, then on the screen with a lot of elements we will see the "jumping" of elements.

Therefore, the coordinates should be changed in viewDidLayoutSubviews, since in this place we can already get the real coordinates / sizes of the surrounding elements, but the elements have not yet been displayed to the user. viewDidLayoutSubviews should be used when the coordinates / dimensions of an element depend on the coordinates or sizes of other elements and these dimensions are difficult to calculate in advance.

    Check out this article. iOS swift - setNeedsLayout vs layoutIfNeeded vs layoutSubviews ()