点击手势子视图触摸检测

时间:2016-05-17 10:30:32

标签: ios objective-c uitapgesturerecognizer

enter image description here

我正在创建抽屉

 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;
}

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

我通过添加两个手势来解决这个问题

@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];

}

}