user4951
user4951

Reputation: 33138

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?

Upvotes: 5

Views: 1451

Answers (1)

rmaddy
rmaddy

Reputation: 318944

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.

Upvotes: 9

Related Questions