UIBarButtonItem: target-action not working?
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];