John Farkerson John Farkerson - 4 months ago 9x
iOS Question

How to call a View Controller programmatically?

I have looked at all the tutorials I can find on this one, and I still don't have the answer. I need to call another view from the code. I am using

. I have changed the view many times by control-dragging from
, but now it must be from the code. I am trying to call the info page from the main menu if it is the first time the user has opened the app. I cannot seem to find a way to change the views from the code, however. All my views are controlled by the same files (ViewController2). The
of my main menu is ViewControllerMain, and the
of the info page is ViewControllerInfo. First I tried this:

[ViewControllerMain presentViewController: ViewControllerInfo
completion: NULL];

Then I tried making different
for each and saying:

[ViewController2 presentViewController: ViewController
completion: NULL];

Neither worked. For the first one, it says:

Use of undeclared identifier ViewControllerMain.

In the second one, it says:

unexpected interface name 'ViewController': expected identifier.

What can I do?


To create a view controller:

UIViewController * vc = [[UIViewController alloc] init];

To call a view controller (must be called from within another viewcontroller):

[self presentViewController:vc animated:YES completion:nil];

For one, use nil rather than null.

Loading a view controller from the storyboard:

NSString * storyboardName = @"MainStoryboard"; 
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"IDENTIFIER_OF_YOUR_VIEWCONTROLLER"];
[self presentViewController:vc animated:YES completion:nil];

Identifier of your view controller is either equal to the class name of your view controller, or a Storyboard ID that you can assign in the identity inspector of your storyboard.