Centering the toolbarItems in a UINavigationController

When you add to the toolbarItems array of your UINavigationController, it puts the items left justified in the toolbar at the bottom of the screen. If you instead want the items to be centered in the toolbar, here is a way to do it…

NSArray *itemArray = @ [ @"Item 1", @"Item 2" ];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(0.0, 0.0, 240.0, 30.0);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
[segmentedControl addTarget:self action:@selector(segmentedControlChanged:) forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *item = [[[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
UIBarButtonItem *flex1 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL] autorelease];
UIBarButtonItem *flex2 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL] autorelease];
self.toolbarItems = @ [ flex1, item, flex2 ];
[segmentedControl release];

The flex1 and flex2 items are just like adding the springs in Interface Builder, which space things out equally across the view. This code is not ARC approved as you can see from the autorelease and release methods, but if you need to use it in an ARC project you should be able to figure it out.

BTW, it looks to be a thin day for actor or musician birthdays, deaths, events, or holidays, so Happy Birthday to President Obama.

Leave a Reply