tags:

views:

515

answers:

3

Hi,

I have a view controller class which loads from a .nib file. However, I also want to add controls (like UISwitch) to that view programmatically (UISwitch is not added to the nib file). In which portion of my code should I allocate the UISwitch control, viewDidLoad or loadView method?

Thanks.

+2  A: 

I would do it on viewDidLoad. Definitely.

From Apple's documentation:

Discussion This method is only invoked when the view property is nil and it is needed for display. You should not invoke this method directly.

If you create the view that this view controller manages programmatically, then you should override this method to create your view. The default implementation creates a UIView object with no subviews.

However, if you initialize the view using a nib file—that is, you set thenibName and nibBundle properties—then you should not override this method because the default implementation already reloads the nib file. Instead override the viewDidLoad method to set any properties after the nib file is loaded.

In your case, the UIView is being created from the NIB file.

Pablo Santa Cruz
A: 

If you are loading from a NIB, implementing loadView will cause an error. Use viewDidLoad. As Pablo says, this is well documented by Apple.

Roger Nolan
+1  A: 

Use viewDidLoad. Additionally you should remove everything you added in the viewDidUnload method.

Lounges