How to load a different storyboard depending on screen size in iOS

- by

As much as I appreciate the idea of Auto Layout, I don’t think it likes me very much. In turn, I don’t like Auto Layout very much. The pain and hassle it takes to make several UI elements fit well on a 4 inch screen as well as a 3.5 inch screen regularly drives me crazy. On paper it’s a great idea – but in reality not fit for prime time.

Screen Shot 2013-12-31 at 08.56.22

It’s not a coincidence that we can choose completely different storyboards for iPads and iPhones. Let’s take the same approach when dealing with the two different iPhone screen sizes by loading different storyboards.

Here’s how: First, finish one version of your storyboard. Next select it and head over to File – Duplicate. Give the second one an appropriate name, then tweak your UI elements so that they look nice on the other screen size.

Now add this to your AppDelegate.m:

- (UIStoryboard *)grabStoryboard {

    UIStoryboard *storyboard;

    // detect the height of our screen
    int height = [UIScreen mainScreen].bounds.size.height;

    if (height == 480) {
        storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        // NSLog(@"Device has a 3.5inch Display.");
    } else {
        storyboard = [UIStoryboard storyboardWithName:@"Main-4in" bundle:nil];
        // NSLog(@"Device has a 4inch Display.");
    }

    return storyboard;
}

This method returns the following UIStoryboard file:

  • Main.storyboard on 3.5inch devices
  • Main-4in.storyboard on 4inch devices

Now we need to make sure it gets loaded appropriately. We’ll take care of it in AppDelegate.m like so:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UIStoryboard *storyboard = [self grabStoryboard];

    // show the storyboard
    self.window.rootViewController = [storyboard instantiateInitialViewController];
    [self.window makeKeyAndVisible];

    return YES;
}

This overrides the default storyboard that’s declared in your project settings. You can expand the above method by checking which iOS Version the device is running, and of course returning an iPad storyboard too.

In your face, “Auto Layout”!

2 thoughts on “How to load a different storyboard depending on screen size in iOS”

  1. I am doing this with iOS7 and it seems to work fine with my iPhone 5 but not with my iPhone 4s. Any suggestions?

  2. Are both phones starting in portrait mode? The height parameter might be reported as the shorter side of the iPhone and hence the pixel check would fail, regardless of the tallness of the screen. Just a thought, I’ve not checked this myself yet but it’s worth looking into.

Add your voice!

This site uses Akismet to reduce spam. Learn how your comment data is processed.