I have a UIButton
that is loaded from a xib file as an IBOutlet
property of a view controller. I attach a selector to the button in the viewDidLoad
of my view controller:
[_myButton addTarget:self action:@selector(mySelector) forControlEvents:UIControlEventTouchUpInside];
In iOS 6 everything works, but when i run on the simulator in iOS 5.0 the selector doesn't get called. The button does highlight when it is touched.
Another thing to note is that the button is in a UIView
that has a UITapGestureRecognizer
added to it. The UITapGestureRecognizer
for this view gets called in iOS 5.0 when the button is tapped, (it does not get called in iOS 6, where the button's selector is called instead).
I don't have a device running iOS 5 so I haven't tested on a device, just the simulator.
Does anyone know what is happening here, and how to solve it?
You have explained very beautifully the cause of the problem. On iOS 5, a UITapGestureRecognizer on a button's superview interferes with the action of the button. On iOS 6, they fixed this: they introduced a UIView event
gestureRecognizerShouldBegin:
, and a button automatically returns NO for a tap gesture recognizer attached to a superview.For iOS 5, you'll need to use a delegate method on the tap gesture recognizer to stop it from recognizing if the tapped view was the button.
In my case, I was also using a general
UITapGestureRecognizer
for dismissing the keyboard opened by a text field when the user would tap anywhere on the main view.I fixed this by only adding a gesture recognizer when the keyboard shows up (see
- (void)keyboardWillShow:(NSNotification *)n
or- (BOOL)textFieldShouldBeginEditing:(VDTextFieldWithError *)textField
)and then removing the gesture recognizer when hiding the keyboard (thus removing the selector in the selector method of the recognizer itself)