简体   繁体   English

如何确定UITapGestureRecognizer触摸了哪个视图?

[英]How to determine which view was touched by UITapGestureRecognizer?

I have a UIScrollView with subviews and a UITapGestureRecognizer . 我有一个带有子视图的UIScrollView和一个UITapGestureRecognizer

I create the recognizer like this: 我像这样创建识别器:

UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognized:)];
[self addGestureRecognizer:tgr];

The view property of UITapGestureRecognizer points to the scroll view itself even if the user touched a different view. 即使用户触摸了不同的视图, UITapGestureRecognizer的view属性UITapGestureRecognizer指向滚动视图本身。 I need to know if touch went down on the scroll view directly. 我需要知道滚动视图中的触摸是否直接下降。

Paul's suggestions are good, but if you don't want (or can't) subclass or become the delegate of the recognizer, there's another way. 保罗的建议很好,但如果你不想(或不能)继承或成为识别器的代表,那么还有另一种方法。

You can ask the gesture recognizer for its locationInView: and then retrieve the view which that point is on top of with your scrollView's hitTest:withEvent: method (defined on UIView). 您可以向手势识别器询问其locationInView:然后使用您的scrollView的hitTest:withEvent:方法(在UIView上定义)检索该点位于其上的视图。 Something like: 就像是:

CGPoint location = [recognizer locationInView:scrollView];
UIView *touchedView = [scrollView hitTest:location withEvent:nil];

You can become either subclass UITapGestureRecognizer and add a new ivar to hold this info by overriding the touchesBegan:withEvent: method something like this 您可以成为子类UITapGestureRecognizer并添加一个新的ivar来通过覆盖touchesBegan:withEvent:方法来保存此信息

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  /*
   * If you wanted you could store a set of all the views to allow
   * for multiple touches
   */
  self.touchedView = [touches.anyObject view];
  [super touchesBegan:touches withEvent:event];
}

Or if you like you can become the delegate for UITapGestureRecognizer and store the tapped view as a property in your class by implementing gestureRecognizer:shouldReceiveTouch: 或者,如果您愿意,您可以成为UITapGestureRecognizer的委托,并通过实现gestureRecognizer:shouldReceiveTouch:将tapped视图存储为您的类中的属性gestureRecognizer:shouldReceiveTouch:

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

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