简体   繁体   English

UIView上的UITapGestureRecognizer及其子视图在点击子视图时一起响应

[英]UITapGestureRecognizer on UIView and Its Subview Respond Together When Subview Is Tapped

UITapGestureRecognizer is applied to both UIImageView and its subview ( UITextView ). UITapGestureRecognizer适用于UIImageView及其子视图( UITextView )。 However, when I tap on subview, the receiver becomes subview and its parent view (ie UIImageView + UITextView ). 但是,当我点击子视图时,接收器变为子视图及其父视图(即UIImageView + UITextView )。 It should however be only subview because that was the one I tapped. 但它应该只是subview,因为那是我点击的那个。 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? 如何在没有可能的子类化和iOS 6+支持的情况下轻松解决我的问题? I tried delaying touch on start for UIGestureRecognizer on UIImageView and I tried setting cancelsTouchesInView to NO - all with no luck. 我尝试在UIImageView上推迟UIGestureRecognizer启动触摸,我尝试将cancelsTouchesInView设置为NO - 一切都没有运气。

Try the following code: 请尝试以下代码:

conform the < UIGestureRecognizerDelegate > to your class. 使< UIGestureRecognizerDelegate >符合您的课程。

set yourGesture.delegate = self ; 设置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. 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. 更通用的解决方案是始终仅为您的parentView设置手势,并且在手势委托中检查坐标是否属于任何一个子视图,如果是,则调用您的子视图的手势方法。 Not a clean approach but works. 不是一个干净的方法,但有效。 !!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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