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)];
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
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With