Tint UIButton and UIBarButtonItem

Tint UIButton and UIBarButtonItem

You may have noticed that the tint property is not available for UIButton and UIBarButtonItem.

Lately, I found a new technique based on UISegmentedControl which you can use the tint property to change the color of your button. This control can be tweaked to have only one segment with a UIButton style (UISegmentedControlStyleBar).

A standard UISegmentedControl

Tweaking the control

We will now create a UISegmentedControl with one segment and set its tint color:

UISegmentedControl *button = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Add", nil]] autorelease];
button.frame = CGRectMake(0, 0, 160, 33);
button.center = self.view.center;
button.momentary = YES;
button.segmentedControlStyle = UISegmentedControlStyleBar;
button.tintColor = UIColorFromRGB(0x0000DD);
[self.view addSubview:button];

Compile your code, your button will look like the following screenshot:

Refer to the UISegmentedControl class reference for a detailled explanation of its properties.

I used a macro in this code to define my tint color. Macro definition is:

#define UIColorFromRGB(rgbValue) [UIColor \
  colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
  green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
  blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

You can read more about defining macro or function here and here.

In a toolbar

You can also use this technique to tint UIBarButtonItem used in UIToolBar.

UIToolbar *toolbar = [[[UIToolbar alloc] init] autorelease];
toolbar.barStyle = UIBarStyleDefault;
[toolbar sizeToFit];
toolbar.frame = CGRectMake(0, self.view.frame.size.height-44, self.view.frame.size.width, 44);
[self.view addSubview:toolbar];
 
/* Create our tinted buttons */
UISegmentedControl *button = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Add", nil]] autorelease];
button.momentary = YES;
button.segmentedControlStyle = UISegmentedControlStyleBar;
button.tintColor = UIColorFromRGB(0x0d9c23);
 
UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
UISegmentedControl *button2 = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Delete", nil]] autorelease];
button2.momentary = YES;
button2.segmentedControlStyle = UISegmentedControlStyleBar;
button2.tintColor = UIColorFromRGB(0xC84131);
UIBarButtonItem *barButton2 = [[[UIBarButtonItem alloc] initWithCustomView:button2] autorelease];
 
[toolbar setItems:[NSArray arrayWithObjects: barButton, barButton2, nil]];

You now have a toolbar with 2 tinted buttons that look like that:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值