[ios] 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 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?

The answer is


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! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

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


You can call ViewController this way, If you want with NavigationController

enter image description here

1.In current Screen : Load new screen

VerifyExpViewController *addProjectViewController = [[VerifyExpViewController alloc] init];
[self.navigationController pushViewController:addProjectViewController animated:YES];

2.1 In Loaded View : add below in .h file

@interface VerifyExpViewController : UIViewController <UINavigationControllerDelegate>

2.2 In Loaded View : add below in .m file

  @implementation VerifyExpViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.delegate = self;
    [self setNavigationBar];
}
-(void)setNavigationBar
{
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"B_topbar.png"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Btn_topback.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonTap:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor lightGrayColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Save.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onSaveButtonTap:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor lightGrayColor];
}

-(void)onBackButtonTap:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)onSaveButtonTap:(id)sender
{
    //todo for save button
}

@end

Hope this will be useful for someone there :)


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.


main logic behind this is_,

NSString * storyboardIdentifier = @"SecondStoryBoard";

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardIdentifier bundle: nil];

UIViewController * UIVC = [storyboard instantiateViewControllerWithIdentifier:@"YourviewControllerIdentifer"];

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

Import the view controller class which you want to show and use the following code

KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
[self presentViewController:viewKart animated:YES completion:nil];

There's 2 ways you can do this:

1, Create a segue to your ViewController in your Storyboard as explained in my answer here: How to perform a segue that is not related to user input in iOS 5?

2, Give your ViewController and identifier and call it using the code in my answer here: Call storyboard scene programmatically (without needing segue)?


        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone_iOS7" bundle:nil];
            AccountViewController * controller = [storyboard instantiateViewControllerWithIdentifier:@"accountView"];
            //            [self presentViewController:controller animated:YES completion:nil];

        UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topRootViewController.presentedViewController)
        {
            topRootViewController = topRootViewController.presentedViewController;
        }

        [topRootViewController presentViewController:controller animated:YES completion:nil];

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to uiviewcontroller

How to set Status Bar Style in Swift 3 UIView touch event in controller How to lock orientation of one view controller to portrait mode only in Swift Programmatically navigate to another view controller/scene Adding a view controller as a subview in another view controller Changing the Status Bar Color for specific ViewControllers using Swift in iOS8 Get top most UIViewController Instantiate and Present a viewController in Swift How to check if a view controller is presented modally or pushed on a navigation stack? Add a UIView above all, even the navigation bar

Examples related to uistoryboard

Xcode 6 Bug: Unknown class in Interface Builder file Prepare for Segue in Swift Best practices for Storyboard login screen, handling clearing of data upon logout iOS: present view controller programmatically How to call a View Controller programmatically? How to use UIScrollView in Storyboard What are Unwind segues for and how do you use them? How to set the UITableView Section title programmatically (iPhone/iPad)? Programmatically set the initial view controller using Storyboards How to Implement Custom Table View Section Headers and Footers with Storyboard

Examples related to presentviewcontroller

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift Swift presentViewController iOS: present view controller programmatically How to call a View Controller programmatically? modal View controllers - how to display and dismiss