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.

5 comments on this post.
  1. Dan:

    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!

  2. Randall:

    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.

  3. How to change the color of UIBarButtonItem on iOS 5 | farp.blog:

    […] most popular blog post is how to change the color of a UIBarButtonItem. It’s something that lots of people want to […]

  4. Simon:

    Confirm, does not tint on 3.x

  5. navigationItemのUIBarButtonItemを好きな色にする « Code? – Design?:

    […] How to change the color of a UIBarButtonItem Filed under: 未分類 Leave a comment Comments (0) Trackbacks (0) ( subscribe to comments […]

Leave a comment