Custom UINavigationBar Back Button

via: http://www.applausible.com/blog/?p=401

A common thing in client apps i write is custom back images, mostly because the apps have a custom UINavigationBar image, so its good to have them themed together. You can see what this looks like for this tutorial:
Ok so in your View Controller, thats shown after something in your navigation view is shown, add this code in the viewDidLoad method:
01- (void)viewDidLoad {
02    [super viewDidLoad];
03 
04    // Set the custom back button
05    UIImage *buttonImage = [UIImage imageNamed:@"back_button.png"];
06 
07    //create the button and assign the image
08    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
09    [button setImage:buttonImage forState:UIControlStateNormal];
10 
11    //set the frame of the button to the size of the image (see note below)
12    button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
13 
14    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
15 
16    //create a UIBarButtonItem with the button as a custom view
17    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
18    self.navigationItem.leftBarButtonItem = customBarItem;
19 
20 // Cleanup
21 [customBarItem release];
22}
Here we load the image we want for the back button in the navigation bar, create a custom UIButton and set the image to the button and then specify that the button is the left button item. I also add a selector to catch clicks, so we know when the user presses back. It calls the back method which quite simply:
1-(void)back {
2    // Tell the controller to go back
3    [self.navigationController popViewControllerAnimated:YES];
4}
And thats it! You can get the project source here – CustomBackButton

Comments