在UIGestureRecognizer处理程序之后,IBAction有时不会被触发

时间:2015-07-20 12:13:26

标签: ios objective-c uigesturerecognizer hittest

我尝试使用UIGestureRecognizer跟踪UI元素上的点击(点按和长按)。跟踪点击后(让我们说通过NSLog记录)UI元素应该完成它的工作。

我正在创建这样的手势识别器:

UITapGestureRecognizer* tap = [[UITapGestureRecognizer] alloc initWithTarget:self action:(OnGesture:)]
tap.cancelsTouchesInView = NO;
tap.delegate = self;
[view addGestureRecognizer:tap];

UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer] alloc initWithTarget:self action:(OnGesture:)]
longPress.cancelsTouchesInView = NO;
longPress.delegate = self;
[view addGestureRecognizer:longPress];

我已经覆盖了一些手势识别器方法:

-(BOOL)gestureRecognizer:(UIGestureRecognizer*)_recognizer shouldReceiveTouch(UITouch*)_touch
{
    return YES;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer*)_recognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)_otherRecognizer
{
    return YES;
}

在手势识别器处理程序中,我试图使用hitTest方法找到水龙头的确切子视图。

-(void)OnGesture:(UIGestureRecognizer*)_recognizer
{
    if([_recognizer.state == UIGestureRecognizerStateEnded])
    {
        if([_recognizer isKindOfClass:[UITapGestureRecognizer class]]
            || [_recognizer isKindOfClass:[UILongPressGestureRecognizer class])
        {
            CGPoint location = [_recognizer locationOfTouch:0 inView:_recognizer.view];                

            // my problem occurs here:
            //---------------------------------------------------------------------------
            UIView* hitView = [_recognizer.view hitTest:location withEvent:nil];
            //---------------------------------------------------------------------------

             NSLog(@"Hit on view: %@", hitView);
         }
    }
}

所以我的问题是:

当我按下UIButton OnGesture方法时,有时(10个案例中有1个)会触发,但是" Touch Up Inside"该按钮的事件未触发。

但是当我评论hitTest时,请致电:

//UIView* hitView = [_recognizer.view hitTest:location withEvent:nil];

错误停止可重现。 IBAction总是被调用。

为什么会这样?我该如何解决这个问题?

P.S。上面的示例代码中可能存在一些拼写错误。

1 个答案:

答案 0 :(得分:0)

根据docs,为了让它起作用:

  

此方法忽略隐藏的视图对象,禁用用户交互或alpha级别小于0.01的视图对象。在确定命中时,此方法不会考虑视图的内容。因此,即使指定的点位于该视图内容的透明部分,仍然可以返回视图。

所以你可能想做self.someSubview.userInteractionEnabled = YES;