Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom back button in UINavigationController

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:

  1. Doubled check that the button backButton is created properly, by adding it to the view hierarchy. It displays properly.
  2. In the same method, changed the title property of the navigationItem 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?

like image 959
pgb Avatar asked Aug 17 '10 19:08

pgb


People also ask

How do I customize the navigation bar in Swift?

Go to the ViewController. swift file and add the ViewDidAppear method. a nav helper variable which saves typing. the Navigation Bar Style is set to black and the tint color is set to yellow, this will change the bar button items to yellow.

What is a UIViewController?

The UIViewController class defines the shared behavior that's common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.


1 Answers

Starting with iOS 5, this is simple:

[[UIBarButtonItem appearance]
            setBackButtonBackgroundImage:[UIImage imageNamed:@"back_button.png"]
            forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

You can place that in your app delegate and it will set the background image to all back buttons in the app (for that control state and bar metrics, of course).

like image 89
Matías R Avatar answered Oct 21 '22 14:10

Matías R