user1624785
user1624785

Reputation: 31

How to create a Objective-C class with two xib files (one for iPhone, another for iPad)

I've created one new screen on my Universal application, called "ScreenSelectLevelViewController", with .h, .m and .xib files. But I wanted to create 2 separated xib files, one for iPhone, another for iPad. So, I duplicate my ScreenSelectLevelViewController.xib and rename both files to these new names:

On my code, I opened the new view like this:

ScreenSelectLevelViewController *newScreen = [[ScreenSelectLevelViewController alloc] initWIthNibName:"@ScreenSelectLevelViewController" bundle:nil];
[self presentModalViewController:newScreen animated:true];

The problem is: when I run on iPhone simulator works, but when I run on iPad Simulator, the application still open the iPhone version of the xib file of this new screen. Someone could help me?

Upvotes: 3

Views: 2159

Answers (2)

rob mayoff
rob mayoff

Reputation: 386018

You can simply rename your files, replacing the underscores with tildes:

ScreenSelectLevelViewController~iphone.xib
ScreenSelectLevelViewController~ipad.xib

Then the code you wrote in your post will automatically load the correct file for the current device.

This is documented under the heading “iOS Supports Device-Specific Resources” in the Resource Programming Guide.

Upvotes: 7

Mick MacCallum
Mick MacCallum

Reputation: 130222

In your app delegate:

- (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];
    }
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

This will tell your application which xib to use when launching, then for opening your new view, you can take what's shown above and apply it:

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    ScreenSelectLevelViewController *newScreen = [[ScreenSelectLevelViewController alloc]        
    initWIthNibName:"@ ScreenSelectLevelViewController_iPhone.xib" bundle:nil];
    [self presentModalViewController:newScreen animated:true];
}
else{
    //same for iPad
}

Upvotes: 1

Related Questions