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

3

17

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?

Millda answered 13/10, 2014 at 21:12 Comment(0)
M
31

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];
Millda answered 13/10, 2014 at 21:14 Comment(3)
You also have to set the size of the button, otherwise it doesn't appear in iOS 7+, [button setFrame:CGRectMake(0, 0, 80, 20)];Threedecker
Or you can let it set its own size: [button sizeToFit];Imbroglio
Does anyone know why this does not work for UINavigation UIBarButtonItems?Cabinetmaker
T
1

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

Tilburg answered 13/10, 2014 at 21:19 Comment(1)
It is Available in iOS 5.0 and later for UIBarButtonItem and it seems to be the only current solution (iOS 9.0)Logomachy
N
1

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!

Nauplius answered 29/11, 2021 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.