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

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

记得前辈以前说过他的习惯是在viewDidLoad中对子view进行初始化,并添加到self.view中;然后在viewWillAppear:中对子view进行layout。具体原因不太理解,最近看到iOS官方推荐的的确是这种做法。

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.

由上面第五条的描述可以看出苹果推荐在viewDidLoad中添加view。

文档中接着又提到:

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.

上面1,2看出iOS是在viewWillAppear:之后对view的layout进行更新,所以可以在viewWillAppear:对view进行布局。