Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIBarButtonItem: target-action not working?

I've got a custom view inside of a UIBarButtonItem, set by calling -initWithCustomView. My bar button item renders fine, but when I tap it, it doesn't invoke the action on my target object.

Here's my code:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"someImage.png"]]; UIBarButtonItem *bbItem = [[UIBarButtonItem alloc] initWithCustomView:imageView]; self.navigationItem.leftBarButtonItem = bbItem; [imageView release]; [bbItem setTarget:self]; [bbItem setAction:@selector(deselectAll)]; 
like image 709
Jacob Relkin Avatar asked May 09 '10 02:05

Jacob Relkin


2 Answers

I do not think the target and action of the UIBarButtonItem apply to custom views. Try using a UIButton instead of UIImageView and applying the target and action to the button.

Sample code in Swift:

let button  = UIButton(type: .Custom) if let image = UIImage(named:"icon-menu.png") {     button.setImage(image, forState: .Normal) } button.frame = CGRectMake(0.0, 0.0, 30.0, 30.0) button.addTarget(self, action: #selector(MyClass.myMethod), forControlEvents: .TouchUpInside) let barButton = UIBarButtonItem(customView: button) navigationItem.leftBarButtonItem = barButton 
like image 57
drawnonward Avatar answered Sep 22 '22 10:09

drawnonward


I had the same problem, but was averse to using a UIButton instead of a custom view for my UIBarButtonItem (per drawnonward's response).

Alternatively, you could add a UIGestureRecognizer to the custom view before using it to initialize UIBarButtonItem; this appears to work in my project.

This is how I would modify your original code:

UIImageView *SOCImageView = [[UIImageView alloc] initWithImage:                              [UIImage imageNamed:@"cancel_wide.png"]];  UITapGestureRecognizer *tapGesture =         [[UITapGestureRecognizer alloc] initWithTarget:self                                                 action:@selector(deselectAll:)]; [SOCImageView addGestureRecognizer:tapGesture];  SOItem.leftBarButtonItem =         [[[UIBarButtonItem alloc] initWithCustomView:SOCImageView] autorelease]; [tapGesture release]; [SOCImageView release]; 
like image 45
Tim Arnold Avatar answered Sep 23 '22 10:09

Tim Arnold