如何在子视图中检测点按手势

如何在子视图中检测点按手势

本文介绍了如何在子视图中检测点按手势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问:如何检测点按手势识别器是否在添加到视图的子视图内?例如。如果我点击一个对象,例如已作为子视图添加到已添加了点按手势识别器的背景的方块,我如何检测到它已被点击?

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)指向withEvent:(UIEvent *)事件以获取对实际子视图的引用被点击,记住您传入的点与视图位于同一坐标空间。

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 属性设置为。许多视图,例如 UILabel ,默认设置为。所以在上述之前:

For hit testing to work the view needs to have the userInteractionEnabled property set to YES. Many views, such as UILabels have this set to NO by default. So prior to the above:

self.subviewOfInterest.userInteractionEnabled = YES;

这篇关于如何在子视图中检测点按手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:19