For an application I'm developing, I need to display a custom back button in a navigation bar. I have the button asset as a PNG image, and I'm writing this code:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 79, 29.0);
[backButton setImage:[UIImage imageNamed:@"button_back.png"] forState:UIControlStateNormal];
self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
}
When I push this view controller, the custom button does not show up, and instead I get the standard back button with the title of this view controller inside.
Things I already tried:
- Doubled check that the button
backButton
is created properly, by adding it to the view hierarchy. It displays properly. - In the same method, changed the
title
property of thenavigationItem
and confirmed that it changes (as expected) the content of my back button.
Can anyone spot what I'm doing wrong? Did anyone succeed in using a custom image as the back button on with a UINavigationController
?
See this answer here: How to create backBarButtomItem with custom view for a UINavigationController
You just need to set the
backBarButtonItem
property on the navigationController before pushing the viewController. Setting thebackBarButtonItem
property in the viewController'sviewDidLoad
method (for example) doesn't work.I do not think that ViewController itself should know anything about its back button According to OOP this is the responsibility of containerViewController in which your view controller is inserted, for example UINavigationController.
Subclass your NavigationController and overload in it superClass method like this:
As @pgb suggested you can use leftBarButtonItem instead of back button item. And to remove the default back button item set it to nil like follows;
Confusingly
backBarButtonItem
is not what you're looking for.It just controls the title on the back button for the next view controller. What you want is to set the
leftBarButtonItem
to your custom back button.