Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align UIBarButtonItem in UIToolbar in iOS universal app?

I want to put two UIBarButtonItem instances to UIToolbar in my iOS universal app, on which the first item is on the left-edge of the toolbar and the second is on the center. However, it looks like this cannot be done in Interface Builder, because the auto layout doesn't support forcing constraints on UIBarButtonItem class due to the fact that it is not a subclass from UIView.

Notice that I don't want to put the first on the left-edge and the second is on the right-edge - I have to put the second button at the center. Also, I don't have a plan to use the third button in order to align them as left, center, and right at equal interval.

Is it still possible to add such constraint in this situation in storyboard? I use Xcode 6 beta 5.

like image 950
Blaszard Avatar asked Sep 10 '25 04:09

Blaszard


2 Answers

You can do it all in your Storyboard.

Select a Bar Button Item in the Object library and drag it into your Toolbar. Add a Flexible Space Bar Button Item at its right. Add your second Bar Button Item at its right. Then, add a second Flexible Space Bar Button Item at its right.

The result will look like this in Interface Builder:

enter image description here

If necessary, you can add an extra Fixed Space Bar Button Item at the right edge of your Toolbar to be sure that your second Bar Button Item is really centered.

User lxt gives another example of this in answer for a similar question here.

Edit: Be sure that your UIToolbar has good constraints before proceeding!

like image 146
Imanou Petit Avatar answered Sep 12 '25 18:09

Imanou Petit


you can do this programmatically

UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"item1" style:UIBarButtonItemStylePlain target:self action:nil];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithTitle:@"item2" style:UIBarButtonItemStylePlain target:self action:nil];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithTitle:@"item3" style:UIBarButtonItemStylePlain target:self action:nil];

self.toolbarItems = [NSArray arrayWithObjects: item1, flexible, item2, flexible, item3, nil];

check this link if you want more details

How to place UIBarButtonItem on the right side of a UIToolbar?

like image 41
Mohamad Chami Avatar answered Sep 12 '25 18:09

Mohamad Chami