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

时间:2013-08-27 00:17:09

标签: iphone ios uigesturerecognizer uitapgesturerecognizer

我有UIScrollView个子视图和UITapGestureRecognizer

我像这样创建识别器:

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

即使用户触摸了不同的视图,UITapGestureRecognizer的view属性也指向滚动视图本身。我需要知道滚动视图中的触摸是否直接关闭。

2 个答案:

答案 0 :(得分:2)

保罗的建议很好,但如果你不想(或不能)继承或成为识别器的代表,还有另一种方法。

您可以向手势识别器询问其locationInView:,然后使用您的scrollView的hitTest:withEvent:方法(在UIView上定义)检索该点位于其上的视图。类似的东西:

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

答案 1 :(得分:1)

您可以成为子类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];
}

或者,如果您愿意,您可以成为UITapGestureRecognizer的代表,并通过实施gestureRecognizer:shouldReceiveTouch:

将点按的视图存储为您班级中的媒体资源