问题描述
快速问题:我如何检测点击手势识别器是否在它添加到的视图的子视图中?例如.如果我点击一个对象,例如一个作为子视图添加到背景中的对象,该背景已经添加了点击手势识别器,我如何检测它已被点击?
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?
推荐答案
当您使用 -locationInView 为您希望的任何视图调用处理程序方法时,您可以抓住手势识别器的点击点:代码>.然后,在 UIView 上使用以下方法:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
获取对被点击的实际子视图的引用,记住点您传入的坐标空间与视图相同.
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.
一些帮助您入门的代码:
Some code to get you started:
CGPoint point = [tapGestureRecognizer locationInView:parentView];
UIView *tappedView = [parentView hitTest:point withEvent:nil];
为了使命中测试工作,视图需要将 userInteractionEnabled
属性设置为 YES
.许多视图,例如 UILabel
s 默认设置为 NO
.所以在上述之前:
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:
self.subviewOfInterest.userInteractionEnabled = YES;
这篇关于如何检测子视图中的点击手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!