3

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.

1
  • Did you embed "Navigation Controller" in your storyboard? If you don't have storyboard, how are you showing FirstViewController? Commented Jun 17, 2017 at 18:17

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.