Following up on this question, where the accepted answer describes a way to globally customize the UINavigationController
's back button, using this code in the implementation of a category named UINavigationItem+MyBackButton.h
:
#import "UINavigationItem+MyBackButton.h"
@implementation UINavigationItem (MyBackButton)
-(UIBarButtonItem*)backBarButtonItem
{
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle: @"Back Button Text"
style: UIBarButtonItemStyleBordered
target: nil action: nil];
return [backButton autorelease];
}
@end
This code works fine for me as long as I only want to customize the title. When I want to get down and dirty and try to customize the background image, just nothing happens and I all I get the default back button showing the title
of the previous UIViewController
on the stack:
- (UIBarButtonItem *)backBarButtonItem
{
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *backButtonImage = [UIImage imageNamed:@"back"];
[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
backButton.frame = CGRectMake(0, 0, 18, 27); // CGRectMake(0, 0, 23, 36);
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:backButton] ;
[backBarButton setTarget:nil];
return backBarButton;
}
I also tried to use UIAppearance
with this code:
UIImage *imgBack = [[UIImage imageNamed:@"back"] resizableImageWithCapInsets:UIEdgeInsetsMake(-6, 22, -6, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:imgBack forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
But this just resulted in a distorted version of the back button that also still showed the title
of the previous UIViewController
.
So, my question is what is the easiest way to globally customize my back button such that it doesnt show the title of the previous UIViewController
but rather only my custom image?
NOTE: I would like to avoid subclassing UINavigationController
as well as having to set the back button explicitly within every UIViewController
, actually the following code will work for this, if placed e.g. in viewDidLoad
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *backButtonImage = [UIImage imageNamed:@"back"];
[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
backButton.frame = CGRectMake(0, 0, 18, 27);
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
self.navigationItem.leftBarButtonItem = backBarButton;
So, what I am looking for is a truely global way to customize the back button exactly once.