UIButton not calling action in iOS 5 but works in iOS 6

孤者浪人 提交于 2020-01-12 02:43:13

问题


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?


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/14364272/uibutton-not-calling-action-in-ios-5-but-works-in-ios-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!