2011-02-28 179 views
4

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

我做了这样的事情:

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

+2

我觉得这是更好的办法。 http://stackoverflow.com/questions/7175086/iphone-single-tap-gesture-conflicts-with-double-one – KJLucid

回答

0

Maby你可以使用一些时间间隔。等待调度事件(x)ms。如果在该时间段内有两次敲击,请分配一次双击。如果您只获得一次调度单击。

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]; 
+0

很酷,这工作!谢谢 – RVN

+0

要在您的文章中添加代码,请为每行提供一个制表符空间,或者使用顶部的代码选项并将代码粘贴到该空间中 – RVN

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