How can I change the background color of a UIBarBu

2020-08-11 04:53发布

问题:

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:

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

回答1:

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];


回答2:

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