【iOS】为什么要在viewDidLoad 中加载view,在viewWillAppear:中对view进行layout?

为什么要在viewDidLoad 中加载view,在viewWillAppear:中对view进行layout?


View Controller Programming Guide for iOS中提到:

As part of the loading process, UIKit performs the following sequence of tasks:

  1. Instantiates views using the information in your storyboard file.
  2. Connects all outlets and actions.
  3. Assigns the root view to the view controller’s view property.
  4. Calls the view controller’s awakeFromNib method.
    When this method is called, the view controller’s trait collection is empty and views may not be in their final positions.
  5. Calls the view controller’s viewDidLoad method.
    Use this method to add or remove views, modify layout constraints, and load data for your views.



Before displaying a view controller’s views onscreen, UIKit gives you some additional chances to prepare those views before and after they are onscreen. Specifically, UIKit performs the following sequence of tasks:

  1. Calls the view controller’s viewWillAppear: method to let it know that its views are about to appear onscreen.
  2. Updates the layout of the views.
  3. Displays the views onscreen.
  4. Calls the viewDidAppear: method when the views are onscreen.