点击手势子视图触摸检测

Tap Gesture subview touch detect

我正在创建抽屉

 self.isShowMenuVC = NO;
_menuView = [MenuViewController viewController];
[self.menuView setDelegate:self];
[self addChildViewController:self.menuView];
[self.menuView.view setFrame:CGRectMake(-kMenuTableWidth, 0, kMenuTableWidth, self.view.frame.size.height)];
[self.view addSubview:self.menuView.view];
[self.menuView didMoveToParentViewController:self];

UITapGestureRecognizer *outsideTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(outsideTapped:)];
[self.view addGestureRecognizer:outsideTap];
outsideTap.delegate = self;

当点击按钮时,我只是将 _menuView.view 的框架设置为像抽屉一样工作

我想要检测抽屉外的触摸,但我做不到

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if (touch.view == self.menuView.view) {
    NSLog(@"Touch Drawer");
} else {
    NSLog(@"Touch Outside");
}

return YES;
}

但总是显示 触摸外部

我遗漏了一些东西但不知道是什么提前谢谢

也尝试使用 2 个手势但无法正常工作,因为 self.view 中有一个手势所以,当我点击抽屉方法调用 2 次时。

为此我尝试禁用一个手势,仍然调用了两次

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

if (gestureRecognizer == self.touchInDrawer) {
    NSLog(@"Touch in drawer");
    [self.touchOutSideDrawer setEnabled:NO];
} else {
    NSLog(@"Outside");
    [self hideMenuView];
}
return YES;
}

UITapGestureRecognizer 无法检测到其所属视图外的触摸。

您需要创建另一个 UITapGestureRecognizer 并将它们添加到 self.menuView.view。

你也可以为你的手势识别器制作两个@属性,并在方法中检查它们:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if (gestureRecognizer == self.firstGesture) {
    NSLog(@"Touch in first gesture");
} else {
    NSLog(@"Touch in another gesture");
}

我已经通过添加两个手势解决了这个问题

@property (strong,nonatomic)        UITapGestureRecognizer          *touchInDrawer;
@property (strong,nonatomic)        UITapGestureRecognizer          *touchOutSideDrawer;

根据@Eugene Zaychenko 的回答,但仍然存在问题,因为委托方法调用了两次

我也不能 [self.touchOutSideDrawer setEnabled:NO]; 在轻触抽屉时,因为如果 [self.touchOutSideDrawer setEnabled:YES];

之后它将从视图中移除并且再也不会执行

但最有趣的是

_touchInDrawer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(outsideTapped:)];
[self.menuView.view addGestureRecognizer:self.touchInDrawer];
self.touchInDrawer.delegate = self;

_touchOutSideDrawer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(outsideTapped:)];
[self.view addGestureRecognizer:self.touchOutSideDrawer];
self.touchOutSideDrawer.delegate = self;

outsideTapped 方法仅调用一次,所以我将所有代码移到那里并且正在运行

- (void) outsideTapped:(UITapGestureRecognizer *)gestureRecognizer {

if (gestureRecognizer == self.touchOutSideDrawer) {
    //  [self.view removeGestureRecognizer:self.touchOutSideDrawer];
    [self hideMenuView];
    NSLog(@"Outside");

} else {
    NSLog(@"Touch in drawer");

    // [self.touchOutSideDrawer setEnabled:NO];

}

}