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:
Isn't the simplest solution just to design it from your storyboard with whatever image or colors you want, and just drag a new action to your controller?
Swift Code
@IBAction func backButton(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) }
I'm reposting my solution from https://stackoverflow.com/a/16831482/171933:
I create a simple category on UIViewController
:
UIViewController+ImageBackButton.h
#import <UIKit/UIKit.h>
@interface UIViewController (ImageBackButton)
- (void)setUpImageBackButton;
@end
UIViewController+ImageBackButton.m
#import "UIViewController+ImageBackButton.h"
@implementation UIViewController (ImageBackButton)
- (void)setUpImageBackButton
{
UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 34, 26)];
[backButton setBackgroundImage:[UIImage imageNamed:@"back_arrow.png"] forState:UIControlStateNormal];
UIBarButtonItem *barBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
[backButton addTarget:self action:@selector(popCurrentViewController) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = barBackButtonItem;
self.navigationItem.hidesBackButton = YES;
}
- (void)popCurrentViewController
{
[self.navigationController popViewControllerAnimated:YES];
}
@end
Now all you have to do is #import UIViewController+ImageBackButton.h
in either all of your view controllers or in a custom base view controller class that your other view controllers inherit from and implement the viewWillAppear:
method:
- (void)viewWillAppear:(BOOL)animated
{
[self setUpImageBackButton];
}
That's all. Now you have an image back button everywhere. Without a border. Enjoy!
The backBarButtonItem
property works as intended, but it will always add its standard button shape and color based on the navigation bar tint color.
You can customize the text, but not replace the image.
One workaround, as Andrew Pouliot suggested, is to use leftBarButtonItem
instead, but I stuck to the standard button instead.
Simply create a UIBarButtonItem
instead of an embedded UIButton
in UIBarButtonItem
. Works fine!
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"button_back.png"] style:UIBarButtonItemStyleBordered target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;