Adding back button to navigation bar

4thSpace picture 4thSpace · May 17, 2010 · Viewed 38.6k times · Source

I've added a navigation bar to a UIViewController. It is displayed from another UIViewController only. I'd like to have a left side back button that is shaped similar to an arrow, just like the normal navigation bar back button. It seems I can only add a bar button through IB. I'm guessing the back button needs to be added programmatically. Any suggestions on how I should do this?

Currently, in the RootController, I push another UIViewController (viewB) by simply doing an addSubView. In viewB, I want to display the navigation bar. The app is view based, not navigation controller based.

Answer

Alex Reynolds picture Alex Reynolds · May 17, 2010

If you're using a navigation controller:

MyViewController *_myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[[self navigationController] pushViewController:_myViewController animated:YES];
UIBarButtonItem *_backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.backBarButtonItem = _backButton;
[_backButton release], _backButton = nil;
[_myViewController release], _myViewController = nil;

If you're not using a navigation controller, look into the Three20 style components to make custom bar buttons.