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

- by

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.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

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