Here's what you need to do to easily make a custom back button that replicates the look of the default back button on iPhone and iPad, with code written out explicitly because I imagine I'll come here looking for this again at some point.
Put the following functions somewhere in the implementation (.m) file of the relevant UIViewController with a UINavigationController, and then in viewDidLoad run [self setupBackButton];
Whatever you'd like to do with the back button, put in the backButtonPressed
function.
- (void)setupBackButton {
UIImage *leftArrowImage;
UIImage *pressedLeftArrowImage;
UIButton *customBackButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 48, 30)];
[customBackButton setAutoresizingMask:UIViewAutoresizingNone];
customBackButton.titleLabel.font=[UIFont boldSystemFontOfSize:12];
[customBackButton setTitle:@"Back" forState:UIControlStateNormal];
[customBackButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[customBackButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
leftArrowImage = [UIImage imageNamed:@"UINavigationBarSilverBack.png"];
pressedLeftArrowImage = [UIImage imageNamed:@"UINavigationBarSilverBackPressed.png"];
}
else {
leftArrowImage = [UIImage imageNamed:@"UINavigationBarDefaultBack.png"];
pressedLeftArrowImage = [UIImage imageNamed:@"UINavigationBarDefaultBackPressed.png"];
}
UIImage *stretchableLeftArrowImage = [leftArrowImage stretchableImageWithLeftCapWidth:15.0 topCapHeight:0];
UIImage *stretchablePressedLeftArrowImage = [pressedLeftArrowImage stretchableImageWithLeftCapWidth:15.0 topCapHeight:0];
[customBackButton setBackgroundColor:[UIColor clearColor]];
[customBackButton setBackgroundImage:stretchableLeftArrowImage forState:UIControlStateNormal];
[customBackButton setBackgroundImage:stretchablePressedLeftArrowImage forState:UIControlStateHighlighted];
[customBackButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *aCustomBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customBackButton];
[[self navigationItem] setLeftBarButtonItem:aCustomBackButtonItem];
}
- (void)backButtonPressed:(id)sender {
NSLog(@"back button pressed");
}
To get the exact button pngs from iOS, I recommend the UIKit Artwork Extractor. After running the project and saving the images on iPad Retina simulator followed by the iPad non-retina simulator, look for the titles in the 'Common' folder in the simulator folder that will appear on your desktop. File names "UINavigationBar...Back(@2x).png" and "UINavigationBar...BackPressed(@2x).png" are what you want.
I'm also attaching the default iOS (iPhone and iPad) back bar button pngs used in the code above as a convenience. Note that with iOS updates, the look of the default back barbuttonitems may change...