本文包含對這篇文章的總結與思考loadView vs viewDidLoad FOR PROGRAMATIC UI SETUP
ViewController的生命周期中各方法執(zhí)行流程如下:init—>loadView—>viewDidLoad—>viewWillAppear—>viewDidAppear—>viewWillDisappear—>viewDidDisappear—>viewWillUnload->viewDidUnload—>dealloc
loadView和viewDidLoad的區(qū)別就是蹦锋,loadView時view還沒有生成站绪,viewDidLoad時慌盯,view已經(jīng)生成了,loadView只會被調用一次撰茎,而viewDidLoad可能會被調用多次(View可能會被多次加載)
參考Apple文檔中的說法:
If you prefer to create views programmatically, instead of using a storyboard, you do so by overriding your view controller’s loadView method. Your implementation of this method should do the following:
Create a root view object. …
Create additional subviews and add them to the root view.
For each view, you should:
- Create and initialize the view.
- Add the view to a parent view using the addSubview: method.
If you are using auto layout, assign sufficient constraints to each of the views you just created to control the position and size of your views. Otherwise, …
Assign the root view to the view property of your view controller.
If you cannot define your views in a storyboard or a nib file, override the loadView method to manually instantiate a view hierarchy and assign it to the view property.
…
You can override [the loadView] method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property.
…
If you want to perform any additional initialization of your views, do so in the viewDidLoad method.
對上述文檔的總結:
如果使用了storyboard或者nib,對view的其他操作在 viewDidLoad里面進行,viewDidLoad對view進行只讀操作
若使用代碼創(chuàng)建view旭绒,則在loadView里面進行
在loadView中,使用自己的view覆蓋原本view的時候(self.view = CustomView() ) 焦人,不應該調用super.loadView()
當controller是繼承自UIViewController的時候挥吵,上述總結生效,如果是繼承自其他controller(eg:UITableViewController)花椭,view的操作要放在viewDidLoad