Our DNA is written in Swift

Shorter Back Buttons

Today, on the train to the big city, I watched the seventh Standford iPhone Programming lecture and got an answer to a question I’ve been having for a long time.

Can I make the back button shorter in a UINavigationView? I like long titles, but it looks ugly on the back button!

The back button of a view that you pushed on the the navigation stack defaults to the previous view controller’s title. You want to make the title explanatory so a long one is good. But if you push another view controller onto the navigation stack you want the space to have an explanatory title on this one, or you need the space for something else.


My first instinct would have been to do some customization property on the top view controller, but because that’s not how Apple designed it.
Instead you are setting the backBarButtonItem of the navigationItem of the previous view controller.
Every view controller has this navigationItem property that allows you to customize the navigation bar. What I did not fathom, but learned today, is that this customization also extends to the next view controllers back button.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil?
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
	self.title = @"First View Controller";
	// this defines the back button leading BACK TO THIS controller
	UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc]
	self.navigationItem.backBarButtonItem = backBarButtonItem;
	[backBarButtonItem release];
    return self;

Note that target and action of the back button are nil. This leaves the default behavior in place which is, for back buttons, to pop the current view controller from the navigation stack. Don’t mess with that, because otherwise your app might get rejected by Apple on grounds of “violating user expectation“.

Categories: Q&A

Leave a Comment

%d bloggers like this: