简体   繁体   中英

UITapGestureRecognizer on UIView and Its Subview Respond Together When Subview Is Tapped

UITapGestureRecognizer is applied to both UIImageView and its subview ( UITextView ). However, when I tap on subview, the receiver becomes subview and its parent view (ie UIImageView + UITextView ). It should however be only subview because that was the one I tapped. I was assuming nested gestures would react first but apparently parent receives the fist tap and then it goes to child.

So, there are different solutions out there for various scenarios (not similar to mine but rather buttons inside scroll view conflict). How can I easily fix my issue without possible subclassing and for iOS 6+ support? I tried delaying touch on start for UIGestureRecognizer on UIImageView and I tried setting cancelsTouchesInView to NO - all with no luck.

Try the following code:

conform the < UIGestureRecognizerDelegate > to your class.

set yourGesture.delegate = self ;

then add this delegate Method:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // return YES (the default) to allow the gesture recognizer to examine the touch object, NO to prevent the gesture recognizer from seeing this touch object.
    if([touch.view isKindOfClass: [UITextView class]] == YES)] {
        return YES;
    }
    else {
        return NO;
    }
}

Hope it will solve your issue. Enjoy Coding..!!!!

That's exactly what is it supposed to do. View hierarchy is like a tree structure and its traversal during a touch gesture starts from the root node. It is very likely for your parent view to receive gesture first and then its subviews. The traversal skips the nodes for which

userInteractionEnabled = NO.

since, you don't have any code I can't help you to play with this flag. A more general solution is to always set gesture only for your parentView and in the gesture delegates check the coordinates if it belongs to any one of the subview and if yes then call your gesture method for your subview. Not a clean approach but works. !!

您应该实现UIGestureRecognizer委托方法,并在识别出多个手势时将正确的策略应用于手势

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM