iOS How can I use pushviewcontroller with NavigationController(Objective - c)

I want to change view by clicking button with NavigationController

So I added a button to Main.storyboard and write some codes like

@property (weak, nonatomic) IBOutlet UIButton *button;

in my ViewController.m (Created automatically when I made my project)

And I added method

- (IBAction)buttonClicked:(id)sender {

SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self.navigationController pushViewController:secondViewController animated:YES];

}

(I made SecondViewController.m, SecondViewController.h, SecondViewController.xib)

After this, I started the application and clicked the button but the screen didn't change.

Actually, when I added log like

NSLog(@"%@", self.navigationController);

null was printed.

I think I need to add some code about NavigationController to AppDelegate.m but I don't know what to do. Please help me.

2 answers

  • answered 2017-06-17 18:14 Soumen

    Try This,

    in Appdelegate.m

    `- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        // Override point for customization after application launch.
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController"
                                                       bundle:nil];
        UINavigationController *navigation = [[UINavigationController alloc]initWithRootViewController:self.viewController];
        self.window.rootViewController = navigation;
       [self.window makeKeyAndVisible];
       return YES;
    }`
    

    You need to embed Navigation Controller through code or Storyboard.

  • answered 2017-06-17 18:14 Priyam Dutta

    First select your initial viewcontroller in storyboard and embed it in NavigationController. enter image description here

    Then give a storyboard identifier to the second viewcontroller.

    Then lastly instantiate Second ViewController from storyboard and push it.

    - (IBAction)buttonClicked:(id)sender {
    SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    [self.navigationController pushViewController:entryController animated:YES];
    }