How to change the color of a UIBarButtonItem
EDIT: There is a here. Basically what they figured out was that a UISegmentedControl with a style of UISegmentedControlStyleBar looks just like a UIBarButtonItem. A key difference is that UISegmentedControl has a nice tintColor property that you can use to change the colors.
So what I did was take CharlyBr‘s code and put it into a UIBarButtonItem category.
+(UIBarButtonItem*)barButtonItemWithTint:(UIColor*)color andTitle:(NSString*)itemTitle andTarget:(id)theTarget andSelector:(SEL)selector
{
UISegmentedControl *button = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:itemTitle, nil]] autorelease];
button.momentary = YES;
button.segmentedControlStyle = UISegmentedControlStyleBar;
button.tintColor = color;
[button addTarget:theTarget action:selector forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *removeButton = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
return removeButton;
}
You can check out my example project on GitHub.
Dan:
April 21st, 2011 at 7:09 pm
Looks good, except for a couple minor issues.
1. Any workaround for the fact that the action fires on touch down, not touch up?
2. On iOS 3.1.3, I’m not seeing the tint. It works on 4.0. I’m basically just doing self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTint…] in viewDidLoad. Any suggestions?
Thanks!
Randall:
April 23rd, 2011 at 12:58 pm
1. I tried changing the control event to something different from UIControlEventValueChanged but I couldn’t get the selector to fire. You might have better luck than me.
2. I’m not sure why it wouldn’t work in iOS 3. Unfortunately I don’t have the SDK installed or any devices to check.
How to change the color of UIBarButtonItem on iOS 5 | farp.blog:
October 15th, 2011 at 3:45 pm
[…] most popular blog post is how to change the color of a UIBarButtonItem. It’s something that lots of people want to […]
Simon:
November 12th, 2011 at 5:59 pm
Confirm, does not tint on 3.x
navigationItemのUIBarButtonItemを好きな色にする « Code? – Design?:
November 27th, 2011 at 5:34 am
[…] How to change the color of a UIBarButtonItem Filed under: 未分類 Leave a comment Comments (0) Trackbacks (0) ( subscribe to comments […]