How to call a View Controller programmatically? How to call a View Controller programmatically? ios ios

How to call a View Controller programmatically?


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.


You need to instantiate the view controller from the storyboard and then show it:

ViewControllerInfo* infoController = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerInfo"];[self.navigationController pushViewController:infoController animated:YES];

This example assumes that you have a navigation controller in order to return to the previous view. You can of course also use presentViewController:animated:completion:. The main point is to have your storyboard instantiate your target view controller using the target view controller's ID.


Swift

This gets a view controller from the storyboard and presents it.

let storyboard = UIStoryboard(name: "Main", bundle: nil)let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewControllerId") as! SecondViewControllerself.present(secondViewController, animated: true, completion: nil)

Change the storyboard name, view controller name, and view controller id as appropriate.