Navigation Controller Push View Controller

Viewed 175173

Question

How to navigate from one view controller to another simply using a button's touch up inside event?

More Info

What I tried in a sample project, in steps, was:

  1. Create the sample single view application.

  2. Add a new file -> Objective-C Class with XIB for user interface (ViewController2).

  3. Add a button into ViewController.xib and control click the button to ViewController.h to create the touch up inside event.

  4. Go to the newly made IBAction in ViewController.m and change it to this...

    - (IBAction)GoToNext:(id)sender 
    {
        ViewController2 *vc2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];
    
        [[self navigationController] pushViewController:vc2 animated:YES];
    }
    

The code runs without errors and I tested the button's functionality with NSLog. However it still doesn't navigate me to the second view controller. Any help would be appreciated.

14 Answers

Let's Say If you want to go from ViewController A --> B then

  1. Make sure your ViewControllerA is embedded in Navigation Controller

  2. In ViewControllerA's Button click you should have code like this.

@IBAction func goToViewController(_ sender: Any) {

    if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {

        if let navigator = navigationController {
            navigator.pushViewController(viewControllerB, animated: true)
        }
    }
}
  1. Please double check your storyboard name, and ViewControllerB's Identifier mentioned in storyboard for ViewControllerB's View

Look at StoryboardID = ViewControllerB

enter image description here

Swift 4 & 5

let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "yourController") as! AlgoYoViewController
        navigationController?.pushViewController(vc,
                                                 animated: true)
Related