Those of you who have used Auto Layout have encountered situations where you cannot get a real frame, and most of you can find a satisfactory solution after a simple search: Call self.view.layoutifneeded () before you want to get the actual frame. This is a useful but not a good method: extra frame calculation is unnecessary.

Let’s analyze this in terms of the View Controller lifecycle:

viewDidLoad
viewWillAppear
viewWillLayoutSubviews
viewDidLayoutSubviews
viewDidAppear
viewWillDisappear
viewDidDisappearCopy the code

ViewDidLayoutSubviews and viewDidAppear: Auto Layout: viewDidLayoutSubviews, viewDidAppear

  1. ViewDidLayoutSubviews: The current view has laid out the child elements, and the frame has been formed
  2. In viewDidAppear, the rendering system adds the current view to the parent view and displays it on the screen

So, the solution is already there:

  1. Instead of calling layoutSubviews, get frames in viewDidLayoutSubviews and viewDidAppear
  2. If you need to do something big early on, it’s recommended in viewDidLayoutSubviews, where the user hasn’t seen the UI yet and can be more flexible
  3. Note that viewDidLayoutSubviews may be called multiple times, so adding elements and so on should be avoided here
  4. You can do anything you want in viewDidAppear, but some of the things that the user needs to see like animations can only be done here
  5. It is recommended to put all the things you need to do into viewDidAppear as far as possible, so that the user can see the interface as soon as possible, which is the basic principle of human-computer interaction

Back to the question in the title: When do I get the frame right? In viewDidLayoutSubviews and viewDidAppear.