如何将UIGestureRecognizer限制为特定的UIView?

时间:2013-03-12 19:36:21

标签: ios objective-c uikit uigesturerecognizer

我有一组像这样分层的UIViews:

  • 的UIWindow
  • 的UIViewController
  • UIView(涵盖整个窗口;标记:41)
  • UIView(标签:100(涵盖UIView的上半部分(标签:41))
  • UIScrollView(下半部分;标记:126)
  • UIView(涵盖UIScrollView;标记:21)
  • UIView(tag:22)< -----涵盖标签的一部分-21 UIView

顶级UIView(标签:22)是我想要识别水龙头的唯一UIView。使用NSLog,标记始终引用标记:41。

以下是我在ViewController中的代码( -viewDidLoad 方法):

    // Create and initialize a tap gesture  
 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
 tap.numberOfTapsRequired = 1;
 tap.numberOfTouchesRequired = 1;
 [self.view addGestureRecognizer:tap];

这是处理点击的代码(也放在VC中)

- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer {

CGPoint pt = [gestureRecognizer locationInView:self.view];

UIView *v = [self.view hitTest:pt withEvent:nil];
NSLog(@"\n\nx: %ld\ny: %ld\ntag: %d",(long)pt.x, (long)pt.y, self.view.tag);

if ([v isKindOfClass:[SubViewData class]]) {
    NSLog(@"SubViewData!");
    return;
}

}

阅读“事件处理指南”(第32页)我看到第一个属于被点击区域约束的视图是获得命中测试的视图,在这种情况下将是标记:41。我需要标签:22才能获得热门测试,因为还有另一个UIView(标签:100)位于标签的上半部分:41还可识别水龙头......

更新:我添加了处理点击的代码...有没有一种方法可以编程方式拒绝点按,除非它是用于UIVIew标记:22?

1 个答案:

答案 0 :(得分:4)

尝试将其附加到整个视图,实现委托方法

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)sender {
   return (CGRectContainsPoint(self.myTargetView.frame, [sender locationInView:self.view]);
}

如果您有多个UIGestureRecognizers并且您为每个- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)sender { if (self.neededGestureRecognizer == sender) { return (CGRectContainsPoint(self.myTargetView.frame, [sender locationInView:self.view]); } return YES; } 委派,请使用:

{{1}}

匹配'em