How to load different view controller class from a

2019-08-16 04:47发布

问题:

I was developing a screen where i want to load view controllers based on the condition.i.e with respect to condition it should load a particular view controller class from app delegate at the time of application launch.

     if(condition success)
 { 
//Load viewcontroller1 
} else 
{ 
//Load  viewcontroller2
 }

How can i achieve this .Please help me out..

回答1:

Just open Xcode, create a new project, make it Universal (iPad/iPhone) and you'll see an example of this. It creates for you two .xib files. One for iPad and one for iPhone.

Then, the app delegate does this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
    } else {
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
    }

In this case, it uses the same ViewController class (ViewController.h and .m) for both .xibs. However, you can certainly change that, too. Just go into each .xib in the Xcode graphical designer (used to be Interface Builder), select the .xib, select File's Owner and on the Inspector tab (properties ... usually on the right) you can choose a Custom Class from a combo box.

So, if you need a different Objective-C UIViewController subclass for each, you can do that. Remember to change the code above to match, too ([ViewController alloc]).



回答2:

You can see the same done by Apple. Create a Universal Application. In appDelegate you can see

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
} else {
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
}

Based on a condition they load different view controllers.