UIButton touch event falls through to underlying view

我是研究僧i 提交于 2020-01-15 05:42:10

问题


I have created a small UIView which contains two UIButtons. 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 triggered. Looking for advice or suggestions.


回答1:


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...




回答2:


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.




回答3:


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"




回答4:


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.




回答5:


Check out this question.

uibutton-inside-a-view-that-has-a-uitapgesturerecognizer




回答6:


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.



来源:https://stackoverflow.com/questions/4902820/uibutton-touch-event-falls-through-to-underlying-view

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