Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically highlight UIBarButtonItem

after tapping the 'record' BarButtonItem I would like to keep it programmatically highlighted until the recording is over. The highlighting graphics of iOS are very good, therefor I would like to remain or set that state.

Up to now I found 'setSelected' and 'setHighlighted' but these do not work on a UIBarButtonItem. Any suggestions on how to solve this? Thank you in advance, Koen.

like image 904
Ckoeny Avatar asked Nov 25 '11 10:11

Ckoeny


3 Answers

setSelected and setHighlighted work fine on UIControls, but not UIBarButtonItems (which are not UIControls).

I'd recommend using UIBarButtonItem's - (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics (documentation linked) method to change the background image to something that mimics highlighting.

You can also set a custom UIView on the item which also mimics highlighting (see the customView property).

like image 101
Michael Dautermann Avatar answered Nov 04 '22 00:11

Michael Dautermann


If you absolutely want to use the default graphics, you could initialize your button item as

UIBarButtonItem *toggleButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"MyButton" 
                                                                     style:UIBarButtonItemStyleBordered 
                                                                    target:someObject 
                                                                    action:@selector(doSomething:)];

and toggle it with

toggleButtonItem.style = (toggleButtonItem.style == UIBarButtonItemStyleBordered) 
                         ? UIBarButtonItemStyleDone : UIBarButtonItemStyleBordered;

You would also need to use the style property to read the current state.

BOOL isSelected = (toggleButtonItem.style == UIBarButtonItemStyleDone)
like image 31
Patrick Avatar answered Nov 03 '22 22:11

Patrick


If you add a UIBarButtonItem with a UIButton backing it, you can just ask for the CustomView.

UIBarButtonItem with a backing UIButton

UIButton *button = (UIButton *)[self.barButtonItem customView];
[button setSelected:YES];
like image 6
Cameron Lowell Palmer Avatar answered Nov 04 '22 00:11

Cameron Lowell Palmer