Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the main storyboard at runtime

I'd like to be able to simply call [UIStoryboard mainStoryboard] to get either the iPad or iPhone storyboard at runtime.

like image 673
Christian Di Lorenzo Avatar asked Oct 11 '13 21:10

Christian Di Lorenzo


2 Answers

Here's a UIStoryboard category that'll do just this:

UIStoryboard+LDMain.h

#import <UIKit/UIKit.h>

@interface UIStoryboard (LDMain)

+ (instancetype)LDMainStoryboard;

@end

UIStoryboard+LDMain.m

#import "UIStoryboard+LDMain.h"

UIStoryboard *_mainStoryboard = nil;

@implementation UIStoryboard (LDMain)

+ (instancetype)LDMainStoryboard {
    if (!_mainStoryboard) {
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *storyboardName = [bundle objectForInfoDictionaryKey:@"UIMainStoryboardFile"];
        _mainStoryboard = [UIStoryboard storyboardWithName:storyboardName bundle:bundle];
    }
    return _mainStoryboard;
}

@end

Here's a link to the gist

like image 71
Christian Di Lorenzo Avatar answered Oct 16 '22 22:10

Christian Di Lorenzo


You can use [UIStoryboard storyboardWithName:storyboardName bundle:bundle] if the storyboard has not already been loaded.

If it has, though, this will load a new copy.

You can also use viewController.storyboard to get the existing one. If you have a mainWindow as part of your application delegate (you probably do), you can get the rootViewController.storyboard of that.

Something like:

UIApplication *application = [UIApplication sharedApplication];
MyAppDelegate *myAppDelegate = ((MyAppDelegate *)application).delegate;
return myAppDelegate.mainWindow.rootViewController.storyboard;

If not, this might work for you:

UIApplication *application = [UIApplication sharedApplication];
UIWindow *backWindow = application.windows[0];
return backWindow.rootViewController.storyboard
like image 13
Steven Fisher Avatar answered Oct 16 '22 22:10

Steven Fisher