tags:

views:

149

answers:

3

Is there a way to have the UIBarButtonItems in a toolbar space themselves out evenly?

+3  A: 

Drop a Flexible Space bar button item in between your UIBarButtonItems. This is pretty easy to do in IB, look down the bottom of the controls.

If you want to do this programtically, this code should help:

UIBarButtonItem* button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button1" style:UIBarButtonItemStyleBordered target:self action:@selector(button1Action)];
UIBarButtonItem* button2 = [[UIBarButtonItem alloc] initWithTitle:@"Button2" style:UIBarButtonItemStyleBordered target:self action:@selector(button2Action)];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[myToolbar setItems:[NSArray arrayWithObjects:button1, flexibleSpace, button2, nil]];
alku83
Alku, you've changed your answer three times to add all the bits that everyone else is saying! Not cool
h4xxr
Yes, I noticed, and I'm sorry. I misread the question the first time, then went to edit my answer, then realized I could provide a better answer the third time as I had some code available. By the time I'd done all that, you guys had come in and answered it better than my original answers.
alku83
Thanks you, this is an excellent answer, I appreciate the effort you have gone to compile the answer into one area. You are a good man.
BahaiResearch.com
Fair enough! :)
h4xxr
+1  A: 

Yup. Create a UIBarButtonItem with the -initWithBarButtonSystemItem: method using UIBarButtonSystemItemFlexibleSpace, and insert that between each of your actual toolbar items. E.g.:

UIBarButtonItem *flexSpace = [[UIBarButton alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace];
myToolbar.items = [NSArray arrayWithObjects:buttonOne,flexSpace,buttonTwo,flexSpace,buttonThree,nil];
[flexSpace release];
Noah Witherspoon
+2  A: 

Ignore the width on UIBarButtonItem suggestion; this is not the correct approach as recommended by Apple and will not work if you want to add further icons.

The correct approach is to add a "Flexible space" (technically another button!) in between each button. You see it in Interface Builder, or it can be added directly in code if needed.

h4xxr