为什么要在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:
- Instantiates views using the information in your storyboard file.
- Connects all outlets and actions.
- Assigns the root view to the view controller’s view property.
- 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. - 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:
- Calls the view controller’s viewWillAppear: method to let it know that its views are about to appear onscreen.
- Updates the layout of the views.
- Displays the views onscreen.
- Calls the viewDidAppear: method when the views are onscreen.
上面1,2看出iOS是在viewWillAppear:
之后对view的layout进行更新,所以可以在viewWillAppear:
对view进行布局。