views:

6164

answers:

1

I have three UIBarButtonItem created as below. They align left and I'd like to align center so there isn't a gap on the right side. I don't see an align property on UIToolBar. Is there another way to accomplish this?

//create some buttons
UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:@"About" style:UIBarButtonItemStyleBordered target:self action:@selector(showAbout:)];
[toolbar setItems:[NSArray arrayWithObjects:settingsButton,deleteButton,aboutButton,nil]];
//Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];
+25  A: 

Add two UIBarButtonSystemItemFlexibleSpace items to your toolbar, to the left and right of your items

UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, settingsButton,deleteButton,aboutButton, flexibleSpace, nil]];
[flexibleSpace release];

Adding these as you would any other toolbar items will distribute space evenly between the two of them.

nduplessis
There's no real reason to make multiple flexible spaces. You can add the same multiple flexible space object to your toolbar multiple times if you need more than one.
mmc
mmc is correct. In fact, it would probably be perfectly reasonable to make a singleton flexibleSpace and reuse it throughout your product. I have heard it claimed that this was the true original use of singletons: not to enforce program rules, but to reduce overhead.
Amagrammer
Updated the code to use one instance of the flexible space
nduplessis
You forgot to update the release call, should read [flexibleSpace release];
Daniel Hepper
Yeah, sorry, it read [flexibleSpaceLeft release] instead of [flexibleSpace release]. Typo fixed
nduplessis