Loading view controller and viewing hierarchy programmatically in Cocoa Touch without xib

It seems that all Cocoa Touch templates are configured to load the knife.

If I want to start a new project that will use the view controller and load its view (hierarchy) programmatically, rather than from nib / xib, what are the steps for setting up or configuring the template.

I, although all I had to do was implement -loadView, but I have problems every time I try to do this.

+7
iphone cocoa-touch uikit uiviewcontroller
source share
2 answers

The easiest way is to make a fully software user interface. First, you need to edit main.m to look something like this:

int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; UIApplicationMain(argc, argv, nil, @"MyAppDelegate"); [pool release]; return 0; } 

where MyAppDelegate is the name of your application delegation class. This means that an instance of MyAppDelegate will be created at startup, which is usually handled by the main Nib file for the application.

In MyAppDelegate, implement the applicationDidFinishLaunching: method, similar to the following:

 - (void)applicationDidFinishLaunching:(UIApplication *)application { window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; if (!window) { [self release]; return; } window.backgroundColor = [UIColor whiteColor]; rootController = [[MyRootViewController alloc] init]; [window addSubview:rootController.view]; [window makeKeyAndVisible]; [window layoutSubviews]; } 

where MyRootViewController is the view controller for the main view in your window. This should initialize the main window and add to it a view controlled by MyRootViewController. rootController is stored as an instance variable inside the delegate for later reference.

This will allow you to programmatically generate your user interface through MyRootViewController.

+16
source share

UIViews themselves do not have a hierarchy, UINavigationControllers do. So, run one of them and push the UIViewController onto the stack. This should make it the most basic way, without any XIB files. You must be able to use it.

 - (void)applicationDidFinishLaunching:(UIApplication *)application { UINavigationController *navController = [[UINavigationController alloc] init]; UIViewController *viewController = [[UIViewController alloc] init]; // set the properties of viewController here, to make it look like you want [navController pushViewController:viewController animated:NO]; [window addSubview:navController.view]; // Don't forget memory management [navController release]; [viewController release]; [window makeKeyAndVisible]; } 
+3
source share

All Articles