5

当用户触摸视图时,我想检测只是双击/单击。

我做了这样的事情:

- (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 水龙头?

4

3 回答 3

3

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

-(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 ];
    }               
}
于 2011-02-28T11:02:53.130 回答
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];
于 2011-02-28T10:56:53.567 回答
0

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

于 2011-02-28T10:46:16.233 回答