10

I've got a UIView with a NavigationBar and I'd like to add a button which looks like the style of a Back Button. I'm not using a UINavigationController and was wondering if this could be done without it?

The style of the button should look like this: alt text

Thanks

ingh.am
  • 25,981
  • 43
  • 130
  • 177
  • 2
    @casperOne Aside from closing a question nearly 2 years after it was answered, why did you close this? The accepted answer in http://stackoverflow.com/questions/227078 suggests using an image, whereas the answer below by Mike Weller is far more elegant. Not to mention, the answer here will support newer devices (for example, I did not change this code example when the retina display was launched and it still works. An image would show a low-res finish). – ingh.am Feb 18 '13 at 12:10

2 Answers2

16

You need to set up a custom stack of UINavigationItem objects and push them on to the UINavigationBar. This is the only way I know of to get a true back button. I haven't tested this code, but you should do something like this:

UINavigationItem *previousItem =
    [[[UINavigationItem alloc] initWithTitle:@"Back title"] autorelease];

UINavigationItem *currentItem =
    [[[UINavigationItem alloc] initWithTitle:@"Main Title"] autorelease];

[navigationBar setItems:[NSArray arrayWithObjects:previousItem, currentItem, nil]
               animated:YES];

To handle when the buttons are pressed you should set yourself as the navigation bar's delegate and implement the UINavigationBarDelegate delegates.

mowliv
  • 125
  • 1
  • 7
Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • FYI: setting the delegate of a navigationBar managed by a navigationController raises an exception: `*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot manually set the delegate on a UINavigationBar managed by a controller.'` – stigi Mar 25 '13 at 11:18
  • what is the currentItem? – scientiffic Aug 29 '14 at 02:46
1

You can also update this by modifying the backBarButtonItem on the previous view controller (not the currently viewed one).

Greg Martin
  • 5,074
  • 3
  • 34
  • 35
  • Hi, i think your answer can help me in my problem, please how to use the backBarButtonItem in my code, assuming that this is my code in the previous view: -(IBAction)goToRechercherView { rechercherViewController.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:rechercherViewController animated:YES]; } – Malloc Mar 29 '11 at 08:34