How to add a second View Controller

Here’s how you add a new View Controller to your project and switch to it via a segue:

  1. open a new Single View project
  2. add am Objective-C class and select subclass of UIViewController (we’ll call it MyViewController here)
  3. in MyViewController.h, import the other ViewController.h
  4. and vice versa, in ViewController.h, import MyVewController.h too
  5. head over to the storyboard and add a ViewController
  6. in the Identity Inspector select MyViewController as a custom class (it’s set to UIViewController by default)
  7. add a segue from ViewController to MyViewController
  8. give the segue a label (let’s call it toMyView)

So far so good. Now you can kick-off a segue between them like so:

[self performSegueWithIdentifier:@"toMyView" sender:self];

Once you’re done with the MyViewController you can dismiss it and go back to ViewController like so:

[self dismissViewControllerAnimated:YES completion:nil];

Next let’s look at how we can exchange data between both View Controllers.

2 thoughts on “How to add a second View Controller

  1. The only problem with using the segue method to jump to the 2nd view controller is that any data created in the 2nd controller will disappear once you return back to #1 then to #2 again.

    For example: I have a UIDatePicker on controller #2. It will be reset back to default every time I go back to controller #2.

    The ‘dismiss’ as shown does not work. Nothing happens.
    I used this: [self.navigationController popViewControllerAnimated:YES];

    I would really like to know how to get back to the 2nd controller and have all the data still as I left it.

    Any ideas?

Leave a Reply