hachinoBlog

hachinobuのエンジニアライフ

UIBarButtonItemの色を変える方法

UIBarButtonItemは本来、ボタンの色変更が出来ない。
だけど、UIToolbarに突っ込んだ後にUIViewのサブクラスとなった該当のボタンなら色を変えられる。

// Toolbar生成
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 460-44, 320, 44)];
toolbar.barStyle = UIBarStyleBlackTranslucent;
[self.view addSubview:toolbar];
	
UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:self action:@selector(action)];
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:self action:@selector(action)];
UIBarButtonItem *button3 = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:self action:@selector(action)];	
NSArray *items = [NSArray arrayWithObjects:button1, button2, button3, nil];
[toolbar setItems:items];	
[button1 release];	
[button2 release];	
[button3 release];	

// 最後のボタンの色変更
UIView *v = [[toolbar subviews] lastObject];
if([v respondsToSelector:@selector(setTintColor:)]){
       [v performSelector:@selector(setTintColor:) withObject:[UIColor redColor]];
}

これ凄い。
UIViewとして扱われるから当然といえば当然なんだけどこのひらめきは思いつかなかったー。

参考URL
http://d.hatena.ne.jp/ntaku/20110102/1293933313