Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I initialize my viewController on viewDidLoad or viewWillLayoutSubviews

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?

like image 316
user4951 Avatar asked Jan 15 '23 23:01

user4951


1 Answers

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.

like image 156
rmaddy Avatar answered Feb 05 '23 12:02

rmaddy