Luther Baker
Luther Baker

Reputation: 7341

UIToolbar UIBarButtonItem Alignment question

I need to create a UIToolbar that has two UIBarButtonItems. The 1st button must be centered and the 2nd item must be right aligned.

I understand and use Flexible spacing and it works great when I need to balance buttons across the UIToolbar, but with only two buttons, I can't seem to perfectly center the middle button. I've even initialized the view.toolbarItems array with

NSArray *items = [[NSArray alloc] initWithObjects:fixed, flex, center_button, flex, right_button, nil];

and set fixed.width = right_button.width ... but still, the center_button is never perfectly centered.

Upvotes: 3

Views: 5017

Answers (3)

octy
octy

Reputation: 6545

I had the same problem recently and solved it by creating a sort of fake UIBarButtonItem. The key in getting the alignment right was to set the possibleTitles property of both left and right bar buttons to the same value, for example:

[right_button setPossibleTitles:[NSSet setWithObject:@"Abc"]];

// Create this fake (plain) button item on the left, to correct the alignment.
UIBarButtonItem *fake = [[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
[fake setEnabled:NO];
[fake setPossibleTitles:right_button.possibleTitles];

// The array for your toolbar items
NSArray *items = [[NSArray alloc] initWithObjects:fake, flex, center_button, flex, right_button, nil];

Late answer... I hope this can still help.

Upvotes: 9

That Don Guy
That Don Guy

Reputation: 21

The problem is, a UIBarButtonItem's width property seems to always be zero. (I think it is because zero is used as a flag by the system to make it the "appropriate" width. A flex space is the same way.) What you might have to do is to use an image in your right button (that way, you know what its width will be), and replace your fixed space with a "left button" that uses a transparent image of the same size as the right button.

Upvotes: 1

Christopher Pickslay
Christopher Pickslay

Reputation: 17762

It sounds like either your toolbar is not the full width of the screen, or your center_button isn't centered in its frame. Have you tried setting center_button.imageInsets?

Upvotes: 0

Related Questions