Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the background color of a UIBarButtonItem on iOS 7+?

I'd like to indicate that a particular UIBarButtonItem is toggled on or off by changing its background color. Mobile Safari uses this feature to indicate whether private browsing is on or off:

OffOn

How can I do this, since there's no backgroundColor property on UIBarButtonItem?

like image 819
Bill Avatar asked Oct 13 '14 21:10

Bill


2 Answers

Create a UIButton and use it as the custom view for the UIBarButtonItem. Then, set the backgroundColor on the button's layer:

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"Test"];
button.layer.backgroundColor = [UIColor redColor].CGColor;
button.layer.cornerRadius = 4.0;

UIBarButtonItem* buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.toolbarItems = @[buttonItem];
like image 96
Bill Avatar answered Nov 06 '22 08:11

Bill


You could instead just use two images. One for selected and one for unselected

- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics

The above function should help you do this

like image 1
CrashOverride Avatar answered Nov 06 '22 06:11

CrashOverride