Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

iphone - Loading a view controller & view hierarchy programmatically in Cocoa Touch without xib

It seems like all of the Cocoa Touch templates are set up to load a nib.

If I want to start a new project that's going to use a view controller, and load its view(hierarchy) programatically, not from a nib/xib, what are the steps to setting that up or adjusting a template.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's reasonably simple to do completely programmatic user interface generation. First, you need to edit main.m to look something like the following:

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 delegate class. This means that an instance of MyAppDelegate will be created on launch, something that is normally handled by the main Nib file for the application.

Within MyAppDelegate, implement your 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 primary view in your window. This should initialize the main window, and add the view managed by MyRootViewController to it. rootController is kept as an instance variable within the delegate, for later reference.

This should let you programmatically generate your user interface through MyRootViewController.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...