【问题标题】:Detect only double or single tap with UIViews?使用 UIView 仅检测双击或单击?
【发布时间】:2011-02-28 10:42:33
【问题描述】:

我想在用户触摸视图时检测 JUST 双击/单击。

我做了这样的事情:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [touches anyObject];
    CGPoint prevLoc = [touch ]
    if(touch.tapCount == 2)
        NSLog(@"tapCount 2");
    else if(touch.tapCount == 1)
        NSLog(@"tapCount 1");
}

但它总是在 2 次点击之前检测到 1 次点击。如何仅检测 1 / 2 次点击?

【问题讨论】:

标签: ios cocoa-touch uitouch


【解决方案1】:

感谢您的帮助。我也找到了这样的方法:

-(void)handleSingleTap
{
    NSLog(@"tapCount 1");
}

-(void)handleDoubleTap
{
    NSLog(@"tapCount 2");
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSUInteger numTaps = [[touches anyObject] tapCount];
    float delay = 0.2;
    if (numTaps < 2) 
    {
        [self performSelector:@selector(handleSingleTap) withObject:nil afterDelay:delay ];     
        [self.nextResponder touchesEnded:touches withEvent:event];
    } 
    else if(numTaps == 2) 
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];            
        [self performSelector:@selector(handleDoubleTap) withObject:nil afterDelay:delay ];
    }               
}

【讨论】:

    【解决方案2】:

    这将有助于定义单击和双击的方法

    (void) handleSingleTap {}
    (void) handleDoubleTap {}
    

    那么在touchesEnded中你可以根据点击次数调用相应的方法,但只能在延迟后调用handleSingleTap以确保没有执行双击:

    -(void) touchesEnded(NSSet *)touches withEvent:(UIEvent *)event {
      if ([touch tapCount] == 1) {
            [self performSelector:@selector(handleSingleTap) withObject:nil
               afterDelay:0.3]; //delay of 0.3 seconds
        } else if([touch tapCount] == 2) {
            [self handleDoubleTap];
        }
    }
    

    touchesBegan中,取消所有对handleSingleTap的请求,这样第二次点击取消第一次点击对handleSingleTap的调用,只调用handleDoubleTap

    [NSObject cancelPreviousPerformRequestsWithTarget:self
      selector:@selector(handleSingleTap) object:nil];
    

    【讨论】:

    • 要在您的帖子中添加代码,请为每一行提供一个制表符空间,或使用顶部的代码选项并将代码粘贴到该空间中
    【解决方案3】:

    也许你可以使用一些时间间隔。等待 (x)ms 分派事件。如果您在该时间段内获得两次点击,请发送两次点击。如果您只获得一次调度单击。

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2013-05-03
      相关资源
      最近更新 更多