Should I initialize my viewController on viewDidLoad or viewWillLayoutSubviews

一笑奈何 提交于 2019-12-30 09:59:18

问题


I noticed that sometimes on viewDidLoad I got the view size right. Sometimes I don't.

For example

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.pullToRefreshController = [self.pullToRefreshController initWithDelegate:self];
    PO(self.view);
    PO(self.view.superview);
    PO(self.view.superview.superview);
    PO(self.view.superview.superview.superview);

    while(false);
}
-(void)viewWillLayoutSubviews
{
    PO(self.view);
    PO(self.view.superview);
    PO(self.view.superview.superview);
    PO(self.view.superview.superview.superview);
    while (false);
}

at viewDidLoad the size of self.view is still 320 to 480. At viewWillLayoutSubviews that have been fixed.

I wonder what happen in between and where should I initialize stuffs? Or what stuffs should be in viewDidLoad and what stuffs should be in viewWillLayoutSubviews?


回答1:


viewDidLoad is a good place to create and initialize subviews you wish to add to your main view. It is also a good place to further customize your main view. It's also a good place to initialize data structures because any properties should have been set on the view controller by the time this is called. This typically only needs to be done once.

viewWillLayoutSubviews is where you position and layout the subviews if needed. This will be called after rotations or other events results in the view controller's view being sized. This can happen many times in the lifetime of the view controller. You should only layout the views here.



来源:https://stackoverflow.com/questions/13466189/should-i-initialize-my-viewcontroller-on-viewdidload-or-viewwilllayoutsubviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!