Skip to content

Instantly share code, notes, and snippets.

@zoul
Created August 31, 2010 07:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoul/558688 to your computer and use it in GitHub Desktop.
Save zoul/558688 to your computer and use it in GitHub Desktop.
Multiple buttons in UINavigationItem
@interface UINavigationItem (Extensions)
- (void) setRightBarButtonItemsWithTotalWidth: (NSUInteger) width
items: (UIBarItem*) firstItem, ...;
@end
static const NSUInteger kToolbarHeight = 45;
@interface SilentToolbar : UIToolbar {}
@end
@implementation SilentToolbar
- (id) initWithFrame: (CGRect) frame
{
[super initWithFrame:frame];
[self setBarStyle:UIBarStyleBlackOpaque];
[self setBackgroundColor:[UIColor clearColor]];
return self;
}
- (void) drawRect: (CGRect) rect {}
@end
@implementation UINavigationItem (Extensions)
- (void) setRightBarButtonItemsWithTotalWidth: (NSUInteger) width
items: (UIBarItem*) firstItem, ...
{
// Parse arguments.
va_list args;
va_start(args, firstItem);
NSMutableArray *items = [NSMutableArray array];
UIBarItem *item = firstItem;
while (item != nil) {
[items addObject:item];
item = va_arg(args, UIBarItem*);
}
va_end(args);
// Create toolbar with the items and insert it
// as a custom view in place of the right navigation button.
UIToolbar *toolbar = [[SilentToolbar alloc] initWithFrame:
CGRectMake(0, 0, width, kToolbarHeight)];
[toolbar setItems:items animated:NO];
UIBarButtonItem *wrapper = [[UIBarButtonItem alloc]
initWithCustomView:toolbar];
[self setRightBarButtonItem:wrapper animated:NO];
[wrapper release];
[toolbar release];
}
@end
@nameghino
Copy link

How can the width of the items be determined at runtime?
Whenever I try to access the item.width property, it always comes back as 0.
Any pointers appreciated,
Thank you
Nicolas Ameghino

@zoul
Copy link
Author

zoul commented Feb 14, 2011

It’s been quite long since I wrote the code, but if I remember correctly, I had to compute the width beforehand. I found no workaround.

@nameghino
Copy link

Thanks for the answer.
I'm working around it by taking the size of the text in the button and trying to guess the button padding and spacing, but still can't get to optimal results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment