I have created a small UIView
which contains two UIButton
s. The view responds to UITapGesture
events. The Buttons are supposed to respond to TouchUpInside
, however when I tap the buttons the responder is the underlying view and the tap gesture selector is triggere开发者_如何学JAVAd. Looking for advice or suggestions.
You can modify the method that responds to the tap gesture in the orange view:
-(void) handleTapFrom:(UITapGestureRecognizer*) recognizer {
CGPoint location = [recognizer locationInView:orangeView];
UIView *hitView = [orangeView hitTest:location withEvent:nil];
if ([hitView isKindOfClass:[UIButton class]]) {
return;
}
//code that handle orange view tap
...
}
This way if you touch a UIButton, the tap will be ignored by the underlying view.
The right answer (which prevents the tabrecognizer from highjacking any taps and doesn't need you to implement a delegate etc) is found here. I got a lead to this answer via this post.
In short use:
tapRecognizer.cancelsTouchesInView = NO;
"Which prevents the tap recognizer to be the only one to catch all the taps"
Each UIView has an 'exclusiveTouch' property. If it's set to YES the view won't pass the touch down the responder chain. Try setting this property on your UIButtons and see if that makes a difference.
How are the views ordered in the view hierarchy? Also, are you creating the interface in IB? If you hook up the connections properly, this shouldn't be an issue at all...
The problem with this design is that it's similar to embedding one button into another. While you may have a valid reason to do it, you should be more careful with the event flow.
What happens is the gesture recognizer intercepting touches before they reach subviews (the two buttons in your case). You should implement UIGestureRecognizerDelegate protocol, namely, gestureRecognizer:shouldReceiveTouch:
method, and return NO if the touch is inside any of the two buttons. That will prevent the orange view from usurping touches intended for the buttons and the buttons will start to work as expected.
Check out this question.
uibutton-inside-a-view-that-has-a-uitapgesturerecognizer
精彩评论