2010-05-03 59 views

回答

20

您正處在正確的軌道上。在觸摸開始之前,您應該存儲用戶第一次觸摸屏幕的位置。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [touches anyObject]; 
    self.startPosition = [touch locationInView:self]; 
} 

touchesEnded中的類似代碼給你最終的位置。通過比較這兩個位置,您可以確定移動的方向。如果x座標超出了某個容差,則可以左右滑動。

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [touches anyObject]; 
    CGPoint endPosition = [touch locationInView:self]; 

    if (startPosition.x < endPosition.x) { 
     // Right swipe 
    } else { 
     // Left swipe 
    } 
} 

除非想在用戶仍然觸摸屏幕時檢測並跟蹤滑動,否則不需要觸摸移動。也可能值得測試的是,用戶在確定他們已經執行輕掃之前移動了最小距離。

+0

quixoto是正確的,內置GestureRecognizer更好。 – fyasar 2011-06-27 10:53:38

+0

我可以將它用於UITableview嗎? – Mashhadi 2011-09-15 06:11:12

+0

這是相當過時的,使用'UISwipeGestureRecognizer'更清潔(iOS 9) – Cbas 2016-04-14 19:03:08

15

如果您願意定位iPhone OS 3.2或更高版本(所有iPad或更新的iPhone),請使用UISwipeGestureRecognizer對象。它會做到這一點,這是非常酷。

36

您將使用UISwipeGestureRecognizer對象檢測刷卡的觸摸和方向在

的UIView或iPhone SDK的任何地方。

UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeHandle:)]; 
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight; 
[rightRecognizer setNumberOfTouchesRequired:1]; 

//add the your gestureRecognizer , where to detect the touch.. 
[view1 addGestureRecognizer:rightRecognizer]; 
[rightRecognizer release]; 

UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipeHandle:)]; 
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft; 
[leftRecognizer setNumberOfTouchesRequired:1]; 

[view1 addGestureRecognizer:leftRecognizer]; 
[leftRecognizer release]; 

- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer 
{ 
    NSLog(@"rightSwipeHandle"); 
} 

- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer 
{ 
NSLog(@"leftSwipeHandle"); 
} 

我覺得你這個問題更好的解決方案

+0

感謝分享,它的工作原理。 – Signcodeindie 2012-11-05 02:58:56