简体   繁体   中英

How to add a Back button to a NavigationBar?

How do I add the back button to a navigation bar? I know there are some related questions but none of them helped. I'm not using storyboard nor did I start with the Master Detail template. Is there a setting to do this? or do you add it by code? if so what code do I need? Any help is appreciated! THANKS!

You don't need to explicitly add a back button. The button will be added automatically when you push controllers into a UINavigationController. That is, a call as:

[navigator pushViewController: controller animated: ...];

creates a back button.

The back button will appear by default if you use a navigationController correctly. The ViewControllers should be this

NavigationController > FirstViewController > SecondViewController

You will need to create navigationController and instantiate with firstVC as the root. From firstVC you can push secondVC and the back button will be there.

The following placed into appDelegate application didFinishLaunchingWithOptions: will load firstVC initially. Place this after you initialize the window...

   UIViewController *firstVC = [[UIViewController alloc] initWithNibName:@"firstVC" bundle:nil];
   // any setupup of firstVC
   UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:firstVC];
   [self.window setRootViewController:navCon];

Then in your firstVC class if you want to push secondVC

in firstVC.m:

UIViewController *secondVC = [[UIViewController alloc] init];
[self.navigationController pushViewController:secondVC animated:YES];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM