In one project, I needed to present some one-off view controllers so I thought it would be best to put them in their own StoryBoard file and load them in code.
I wrote a method that takes the view controller name (set in the Identity Inspector – see image). In this case it is “browserVC” (I have a separate one for browserVC_iPhone in the same Storyboard file).
It also takes the story board (file) name, in this case the storyboard is named Browser.storyboard. So the call to the method is:
[self loadAndPresentVCNamed:@”browserVC” fromStoryboardNamed:@”Browser”];
Those are passed into the code to create the instance (and present it)…
-(UIViewController*)loadAndPresentVCNamed:(NSString*)vcName fromStoryboardNamed:(NSString*)sbName; { // 1. Get the storyboard UIStoryboard *storyboard = [UIStoryboard storyboardWithName:sbName bundle:nil]; // 2. Edit the vcName if necessary (optional) // If you don't have a separate items in your Storyboard w/ it's Storyboard ID // set to "<vcName>_iPhone", remove the next 2 lines. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) vcName = [NSString stringWithFormat:@"%@_iPhone", vcName]; // 3. Get the controller from the storyboard. UIViewController *controller = (UIViewController *) [storyboard instantiateViewControllerWithIdentifier:vcName]; // 4. Present the vc and return it. [self presentViewController:controller animated:YES completion:nil]; return controller; }
1. The code first gets the story board file into a UIStoryboard pointer.
2. Then, based on the UI idiom, it modifies the vcName if necessary.
3-4. Then it gets the view controller instance and presents it. It returns the controller which you may or may not use.
In this case, the returned controller has a method to load a URL. So for my uses, the method above presents the view controller (which happens to be a ‘browser’) and the calling method can specify what URL to load.