Bill
Bill

Reputation: 45408

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:

Off On

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

Upvotes: 17

Views: 14724

Answers (3)

Kyle Yi
Kyle Yi

Reputation: 468

Swift 5 Answer

        let rightBarCancelButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        let cancelImage = UIImage(systemName: "multiply")
        rightBarCancelButton.setImage(cancelImage, for: .normal)
        rightBarCancelButton.layer.cornerRadius = 15
        rightBarCancelButton.backgroundColor = UIColor.lightGray
        
        let rightBarButton = UIBarButtonItem(customView: rightBarCancelButton)
        navigationItem.rightBarButtonItem = rightBarButton

Works like a charm!

Upvotes: 1

CrashOverride
CrashOverride

Reputation: 669

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

Upvotes: 1

Bill
Bill

Reputation: 45408

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

Upvotes: 31

Related Questions