view的操作在loadView还是viewDidLoad

本文包含对这篇文章的总结与思考loadView vs viewDidLoad FOR PROGRAMATIC UI SETUP

ViewController的生命周期中各方法执行流程如下:init—>loadView—>viewDidLoad—>viewWillAppear—>viewDidAppear—>viewWillDisappear—>viewDidDisappear—>viewWillUnload->viewDidUnload—>dealloc

loadView和viewDidLoad的区别就是,loadView时view还没有生成,viewDidLoad时,view已经生成了,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:

  1. Create a root view object. …

  2. Create additional subviews and add them to the root view.

    For each view, you should:

    1. Create and initialize the view.
    2. Add the view to a parent view using the addSubview: method.
  3. 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, …

  4. Assign the root view to the view property of your view controller.

UIViewController:

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进行只读操作

  • 若使用代码创建view,则在loadView里面进行

  • 在loadView中,使用自己的view覆盖原本view的时候(self.view = CustomView() ) ,不应该调用super.loadView()

  • 当controller是继承自UIViewController的时候,上述总结生效,如果是继承自其他controller(eg:UITableViewController),view的操作要放在viewDidLoad

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容