2011-02-28 322 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 ]; 
    }    
}