Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIBarButtonItem doesn't highlight when tapped if in a Toolbar?

I need two buttons on the left side of a nav bar. The only way I've figured out how to do that is by first putting them into a UIToolbar and then setting the leftBarButtonItem to that.

If I do this it works as normal (you can see it highlight when tapped):

UIBarButtonItem* myBtn = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething:)];

self.navigationItem.leftBarButtonItem = myBtn;

But if I do it like this, the button action still happens but there is no highlight (no visual feedback that you are tapping the button):

 NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:2];

 UIBarButtonItem* myBtn = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething:)];

 UIBarButtonItem* myBtn2 = [[UIBarButtonItem alloc] initWithTitle:@"Button2" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomethingElse:)];

 [buttons addObject:myBtn];
 [buttons addObject:myBtn2];

 UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 133, 44)];
 [toolbar setItems:buttons animated:NO];
 self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar];

Any idea why this causes the buttons to not highlight when touched?

like image 994
sol Avatar asked Nov 06 '22 08:11

sol


2 Answers

I dont think the UIBarButtonItem object will be highlighted when touched up. Even for default back button in the navigation bar dosent highlight when touched up. It works in that way only . Not sure but you can try using UISegmentedControl with the single segment . It might create the highlighted illusion and would look like barbutton only.

like image 99
Bharat Jagtap Avatar answered Nov 10 '22 05:11

Bharat Jagtap


In your selector function (e.g. doSomething), set the tintColor property of the button to your desired highlighted color if pressed, and the default if unpressed. And make sure the highlight color of your button is different than the default color so that you know that it is highlighted.

As per the Apple Docs, the function of showsTouchWhenHighlighted is:

A Boolean value that determines whether tapping the button causes it to glow.

but this is only for UIButton. I don't believe UIBarButtonItem has a highlight option.

Note that UIBarButtonItem inherits from UIBarItem which inherits from NSObject, not UIButton, so you can expect different behavior.

like image 23
Joshua Wolff Avatar answered Nov 10 '22 05:11

Joshua Wolff