I am trying to programmatically create a view controller. I would like to know when I should create the view controller using a NIB file, and when I should create it programmatically.
I would also like step-by-step instructions to create the view controller 开发者_Go百科without a NIB file.
Use the IB when ever you like to. Use code in the remaining cases.
Here is how you can get rid of the IB in the creation of the AppDelegate.
- Remove the entry "Main nib file base name" in the Info.plist
- Change
int retVal = UIApplicationMain(argc, argv, nil, nil);
in main.m toint retVal = UIApplicationMain(argc, argv, nil, @"MyCoolApplicationAppDelegate");
where "MyCoolApplication" is the name of your app. Add in "MyCoolApplicationAppDelegate" in
applicationDidFinishLaunching:application
the following code:window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
To create a view controller without a nib do:
MyCoolViewController *myCoolViewController = [[MyCoolViewController alloc] init];
and in the load view of MyCoolViewController you can add initialize the corresponding view and attach it to the your view controller via:
[self setView: MyCoolView];
Personally, I like to use IB for ViewControllers that contain mostly static views. When a ViewController has a lot of views that I need to create dynamically, or animate I prefer to create the ViewController with code.
See the View Controller Programming Guide for iOS: Understanding the View Management Cycle.
That should tell you when and why the methods are called and in what order.
精彩评论