Instantiating a view controller from a storyboard

A short post today, just to highlight an interesting thing I found.

While working on LocalTalk, I needed to change the transition between two view controllers. Previously it was defined by a segue in the storyboard. The storyboard holds view controllers for all the parts of the app. Once disconnected from the segue one of the view controllers now sat alone and unconnected to the rest of the app flow, though still in the storyboard itself.

So I started coding the custom transition using the iOS7 custom transitions I spoke about before in the Zoomatron project. I soon came to instantiate the view controller and realised that if I  wanted to have it use the various controls and views I had defined in the storyboard I would have to find another way of doing so. 

a standard alloc/init pairing wouldn't do, since it's not in a .xib file the initWithNibName: bundle: wouldn't be called either. In the end, after some reading docs I found that it's possible though far from commonly documented. Here's the code...

    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
LTBrowserViewController *browserViewController = (LTBrowserViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"browserVC"];

The important thing to make sure you do is set the Storyboard ID of the view controller in the storyboard file as this is the reference that makes it all tick. Again this is a little unclear in the documentation. You might want to #define or use a static NSString to hold the value to prevent the mistyping errors that make key-value coding such a pain to debug. 

Hope you find this useful! I put a snippet in Dash for it, here's the template version...

    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
__VC-CLASS__ *__INSTANCE__ = (__VC-CLASS__ *)[mainStoryboard instantiateViewControllerWithIdentifier:__STORYBOARD-ID__];

"Looking to meet: the perfect monospaced font"

My next-gen iOS device wishlist