Skip to content

Instantly share code, notes, and snippets.

@SRandazzo
Created July 16, 2011 20:30
Show Gist options
  • Save SRandazzo/1086743 to your computer and use it in GitHub Desktop.
Save SRandazzo/1086743 to your computer and use it in GitHub Desktop.
Custom UIBarButtonItem for UINavigationBar or UIToolbar
@implementation UIBarButtonItem (CustomBarButton)
+ (UIBarButtonItem*)barItemWithTitle:(NSString *)title backgroundImage:(UIImage *)image target:(id)target action:(SEL)action
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[image stretchableImageWithLeftCapWidth:8 topCapHeight:0] forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
[button.titleLabel setFont:font];
[button.titleLabel setShadowColor:[UIColor whiteColor]];
[button.titleLabel setShadowOffset:CGSizeMake(0, 1)];
CGSize size = [button.titleLabel.text sizeWithFont:font];
float titleWidth = size.width;
//Add 15 to the width for a left-right buffer
[button setFrame:CGRectMake(0.0, 0.0, titleWidth+15, image.size.height)];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}
+ (UIBarButtonItem*)barItemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
return [UIBarButtonItem barItemWithTitle:title backgroundImage:[UIImage imageNamed:@"button_CustomBarButton"] target:target action:action];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment