iPhone SDK: Customizing back button title

When developing navigation controller-based apps, it’s pretty common to want to customize the title of the back button that is displayed on the navigation bar. Usually the button title is set to the parent view controller’s title, but you can customize that.

All you need to do is add some code to the viewDidLoad method in the parent view controller:

- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.title = @"Title goes here";
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    UIBarButtonItem *syncButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh:)];
    self.navigationItem.rightBarButtonItem = syncButton;
    [syncButton release];
 
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationItem.backBarButtonItem = backButton;
    [backButton release];
 
    [self refreshData];
}

Screenshots of the parent and child view controllers are available below:

4 Comments »

  1. Barry E. said,

    March 20, 2009 @ 7:33 am

    Thanks for the example. At first it’s counterintuitive to set the “Back” button in the parent, but makes more sense when you ponder it for a minute. I’ve seen other forums where all sorts of wrong or convoluted answers are given. Yours worked beautifully for me.

  2. iPhonesoft.fr said,

    August 14, 2009 @ 10:23 am

    Hi, i used one of your example for customizing the back button title :)
    i ve put your url in my blog, which is a big one in France about iphone

    http://iphonesoft.fr/livres-et-sources-developpement-iphone

  3. hugh johnson said,

    December 20, 2010 @ 9:38 am

    hi, but would not that leak the memory of previous backBarButtonItem?

  4. Chris Hatton said,

    July 21, 2011 @ 9:16 am

    Hi Hugh,
    To answer your valid concern – no it would not… the reason being that the backbarButton item property is an ‘override’. What this means is that it’s normally null which signals the NavigationController to manage its own internal back button instance. Therefore when you are setting it in this way, you’re not leaking any previous button because there never was one assigned to the property. The normal, internally generated button is memory managed by UINavigationController.

RSS feed for comments on this post · TrackBack URI

Leave a Comment