[ios] Navigation Controller Push View Controller

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.

This question is related to ios objective-c iphone swift

The answer is


AppDelegate to ViewController:

let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let loginPageView = mainStoryboard.instantiateViewControllerWithIdentifier("leadBidderPagerID") as! LeadBidderPage
var rootViewController = self.window!.rootViewController as! UINavigationController
rootViewController.pushViewController(loginPageView, animated: true)

Between ViewControllers:

let loginPageView = self.storyboard?.instantiateViewControllerWithIdentifier("scoutPageID") as! ScoutPage
self.navigationController?.pushViewController(loginPageView, animated: true)

If you are using Swift:

let controller = self.storyboard!.instantiateViewControllerWithIdentifier("controllerID")
self.navigationController!.pushViewController(controller, animated: true)

This is working perfect:

PD: Remember to import the destination VC:

#import "DestinationVCName.h"

    - (IBAction)NameOfTheAction:(id)sender 
{
       DestinationVCName *destinationvcname = [self.storyboard instantiateViewControllerWithIdentifier:@"DestinationVCName"];
    [self presentViewController:destinationvcname animated:YES completion:nil];
}

Create the navigation controller first and provide it as rootViewController of your window object.


UIViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboardId"];
[self.navigationController pushViewController:vc animated:YES];

For Swift use the below code:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window!.backgroundColor = UIColor.whiteColor()

    // Create a nav/vc pair using the custom ViewController class

    let nav = UINavigationController()
    let vc = NextViewController(nibName: "NextViewController", bundle: nil)

    // Push the vc onto the nav
    nav.pushViewController(vc, animated: false)

    // Set the window’s root view controller
    self.window!.rootViewController = nav

    // Present the window
    self.window!.makeKeyAndVisible()
    return true

}

ViewController:

 @IBAction func Next(sender : AnyObject)
{
    let nextViewController = DurationDel(nibName: "DurationDel", bundle: nil)

    self.navigationController.pushViewController(nextViewController, animated: true)
}

Swift 4 & 5

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

-  (void) loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                error:(NSError *)error{
    UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:@"nav"];
    ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"LoggedInVC"];
    [nav pushViewController:vc animated:YES];
    [self presentViewController:nav animated:YES completion:nil];
}

"nav" is the Storyboard ID for my navigation controller "vc" is the Storyboard ID for my first view controller connected to my navigation controller

-hope this helps


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


Use this code in your button action (Swift 3.0.1):

let vc = self.storyboard?.instantiateViewController(
    withIdentifier: "YourSecondVCIdentifier") as! SecondVC

navigationController?.pushViewController(vc, animated: true)

    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"storyBoardName" bundle:nil];
    MemberDetailsViewController* controller = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentiferInStoryBoard"];
[self.navigationController pushViewController:viewControllerName animated:YES];

Swift 4:

let storyBoard = UIStoryboard(name: "storyBoardName", bundle:nil)
let memberDetailsViewController = storyBoard.instantiateViewController(withIdentifier: "viewControllerIdentiferInStoryBoard") as! MemberDetailsViewController
self.navigationController?.pushViewController(memberDetailsViewController, animated:true)

Using this code for Navigating next viewcontroller,if you are using storyboard means follow this below code,

UIStoryboard *board;

if (!self.storyboard)
{
    board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
}
else
{
    board = self.storyboard;
}

ViewController *View = [board instantiateViewControllerWithIdentifier:@"yourstoryboardname"];
[self.navigationController pushViewController:View animated:YES];

UINavigationController is not automatically presented in UIViewController.

This is what you should see in Interface Builder. Files owner has view outlet to Navigation controller and from navigation controller is outlet to actual view;

Interface Builder


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 iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?