How to create a View Controller defined in you your Storyboard programmatically

Your View Controllers are created by the Storyboard automatically depending their defined relationships in Interface Builder.

Sometimes however we need to create and transition to View Controllers we’ve defined in code. For example, if you want to transition to a view as part of displaying a search result.

We can do this by creating a new UIStoryboard object and then asking it to create a View Controller defined in it. For this to work you need to give your View Controller a unique identifier using the Identity Inspector (under Identity, set a Storyboard ID).

This example assumes we have a Storyboard file called MainStoryboard.storyboard in which there’s a View Controller called DetailView. Here’s how we create it and push it onto a stack of Navigation Controllers:

// create the Storyboard object
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailViewController *detailView = [storyboard instantiateViewControllerWithIdentifier:@"DetailView"];

// set properties you'd like the detailView to have (optional)
detailView.someProperty = @"This is great";

// push the new detailView onto the stack
[self.navigationController pushViewController:detailView animated:YES];

Note that you define the Storyboard without its extension. If the bundle parameter is nil (as it is here) then the compiler assumes your main bundle.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.