ios 如何检测子视图中的点击手势
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10459184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect a tap gesture in subviews
提问by Fitzy
Quick question: how do i detect if a tap gesture recognizer is within a subview of the view it is added to? Eg. if i click on an object such as a square that has been added as a subview to a background which a tap gesture recognizer has been added to, how do I detect that it has been tapped?
快速问题:我如何检测点击手势识别器是否在它添加到的视图的子视图中?例如。如果我单击一个对象,例如已作为子视图添加到已添加轻敲手势识别器的背景中的正方形,我如何检测它已被轻敲?
回答by Brandon A
You can grab the point of the tap off the gesture recognizer when your handler method is called respective to any view you wish using -locationInView:
. Then, use the following method on UIView: - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
to get a reference to the actual sub view that was tapped remembering that the point you pass in is in the same coordinate space as the view.
当您的处理程序方法针对您希望使用的任何视图调用时,您可以抓住手势识别器的点击点-locationInView:
。然后,在 UIView 上使用以下方法:- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
获取对被点击的实际子视图的引用,记住您传入的点与视图在相同的坐标空间中。
Some code to get you started:
一些帮助您入门的代码:
CGPoint point = [tapGestureRecognizer locationInView:parentView];
UIView *tappedView = [parentView hitTest:point withEvent:nil];
For hit testing to work the view needs to have the userInteractionEnabled
property set to YES
. Many views, such as UILabel
s have this set to NO
by default. So prior to the above:
要进行命中测试,视图需要将userInteractionEnabled
属性设置为YES
. 许多视图,例如UILabel
sNO
默认设置为。所以在上述之前:
self.subviewOfInterest.userInteractionEnabled = YES;
回答by lu yuan
maybe you should set as: subviews.userInteractionEnabled = YES;good luck!
也许你应该设置为: subviews.userInteractionEnabled = YES; 祝你好运!