How to call a View Controller programmatically?

Samuel Noyes picture Samuel Noyes · Apr 21, 2013 · Viewed 133.8k times · Source

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 UIStoryboards. I have changed the view many times by control-dragging from UIButtons, 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 identifier of my main menu is ViewControllerMain, and the identifier of the info page is ViewControllerInfo. First I tried this:

[ViewControllerMain presentViewController: ViewControllerInfo 
                                 animated:YES 
                               completion: NULL];

Then I tried making different UIViewControllers for each and saying:

[ViewController2 presentViewController: ViewController 
                              animated:YES 
                            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?

Answer

190290000 Ruble Man picture 190290000 Ruble Man · Apr 21, 2013

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.