55

I want to change below code with storyboard with Xcode 4.2.

UIViewController * example     = [[ExampleViewController alloc] initWithNibName:@"ExampleViewController" bundle:nil];

Now ExampleViewController.xib file exist. but I want to make it with storyboard. please help me. (I'm not good at English. Sorry)

2 Answers 2

133

The UIStoryboard class is your friend:

UIStoryboard* sb = [UIStoryboard storyboardWithName:@"mystoryboard"
                                              bundle:nil];
UIViewController* vc = [sb instantiateViewControllerWithIdentifier:@"ExampleViewController"];
3
  • Stephen, thank you! I've been searching for quite some time trying to figure out how to instantiate a Storyboard's view. Your answer (and jokor7's question) are like a fresh glass of water in the middle of the dry Sahara Desert. Jul 17, 2012 at 19:22
  • 5
    It is indeed your friend. If you have only one main storyboard, you don't need to initialize it like above, but can just call: [self.storyboard instantiateViewControllerWithIdentifier:@"<controller_identifier>"];
    – JCoster22
    Nov 12, 2013 at 5:15
  • This did it! perfect for switching from a login view controller to a navigation controller. Thank you Mar 7, 2014 at 7:55
8
  • If it is still in its own xib file, then you don't change anything.
  • If you've moved everything into a storyboard, then you wouldn't often need to do this as you'd link between view controllers using segues.

If neither of the above are true, i.e. your view controller is on the storyboard but no segue connects to it, then you want UIStoryboard's instantiateViewControllerWithIdentifier: method described in the documentation. You have to set the identifier in the storyboard for this to work.

3
  • thanks @jrturton ^^ My view controller is on the storyboard but no segue to it. And change initWithNibName code to 'UIViewController *example = [self.view instantiateViewControllerWithIdentifier:@"ExampleView"];'. But it has error. Is not equal both codes?
    – jokor7
    Jan 13, 2012 at 15:52
  • 1
    @jokor7 You don't send instantiateViewControllerWithIdentifier: to self.view or any other view, you send it to a storyboard. More specifically, you need to send it to the storyboard that contains the view controller. See the UIStoryboard class, please.
    – Caleb
    Jan 13, 2012 at 16:37
  • @jokor7 can't add anything more to Caleb's comment really. With that and stephen's answer you should have everything you need.
    – jrturton
    Jan 13, 2012 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.