Saturday, March 26, 2011

How to Define Custom backBarButtonItem

When you push a UIViewController into navigation stack, there is a default "back" button with the title of previous view. Sometimes the title is too long or text is not quite right. Then you need to define your own.

Fortunately it's easy. The problem is where to do it.

Every UIViewController has a default back button, but it never uses its own. Back button you see on-screen belongs to the previous view. In other words, viewController's back button is used only when returning to this view from elsewhere. Therefore when you want to change back button, do it in the "previous" view.
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *backButton =
      [[UIBarButtonItem alloc]
        initWithTitle:@"My Back"
        style:UIBarButtonItemStyleBordered
        target:nil
        action:nil];
    self.navigationItem.backBarButtonItem = backButton;
    [backButton release];
}
Other ways:
  • You can change previous view title in viewDidDisappear, but unfortunately you can see back button text change on-screen. Additionally you need to restore original title in viewWillAppear.
  • You can define custom leftBarButtonItem in current view's viewWillAppear, but button shape will be rectangle. Normally back button has arrow like shape pointing left. You could fix this by using custom graphics as button image(s).

4 comments:

  1. Thanks for sharing. This is useful as the title of the Back button should not always be the default one.

    ReplyDelete
  2. This solution is not work for me....

    ReplyDelete
  3. Thank you for your great solution. One more question is, the background color is still the bluish default color.

    How to customize the color?

    Thank you in advance!

    ReplyDelete
  4. Which color? Have you tried setting either tintcolor or background color? Also since iOS5 there is e.g. UIBarMetrics.

    ReplyDelete