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)

jokor7
  • 611
  • 1
  • 6
  • 8

2 Answers2

133

The UIStoryboard class is your friend:

UIStoryboard* sb = [UIStoryboard storyboardWithName:@"mystoryboard"
                                              bundle:nil];
UIViewController* vc = [sb instantiateViewControllerWithIdentifier:@"ExampleViewController"];
Cœur
  • 37,241
  • 25
  • 195
  • 267
Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
  • 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. – Jonathan Beebe Jul 17 '12 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:@""];` – JCoster22 Nov 12 '13 at 05:15
  • This did it! perfect for switching from a login view controller to a navigation controller. Thank you – Alex Nolasco Mar 07 '14 at 07: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.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • 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 '12 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 '12 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 '12 at 16:57