2011-01-28 87 views
30

任何想法,如果有一種方法來獲得滑動手勢或觸摸的長度,以便我可以計算距離?UISwipeGestureRecognizer滑動長度

+0

我想你只能得到方向fr om UISwipeGestureRecognizer。也許你可以獲得觸摸開始和結束的位置,並從中計算長度。 – picknick 2011-01-28 14:17:30

回答

53

由於SwipeGesture會在手勢結束時觸發一次您可以準確訪問位置的方法,因此無法與滑動手勢保持一定的距離。
也許你想使用UIPanGestureRecognizer。

如果可以使用平移手勢,則可以保存平底鍋的起始點,如果平底鍋已經結束計算距離。

- (void)panGesture:(UIPanGestureRecognizer *)sender { 
    if (sender.state == UIGestureRecognizerStateBegan) { 
     startLocation = [sender locationInView:self.view]; 
    } 
    else if (sender.state == UIGestureRecognizerStateEnded) { 
     CGPoint stopLocation = [sender locationInView:self.view]; 
     CGFloat dx = stopLocation.x - startLocation.x; 
     CGFloat dy = stopLocation.y - startLocation.y; 
     CGFloat distance = sqrt(dx*dx + dy*dy); 
     NSLog(@"Distance: %f", distance); 
    } 
} 
+1

非常感謝這個主意! – Tomo 2011-01-29 10:26:33

+0

應該`sqrt`是`sqrtf`? – ZeR0 2013-01-29 13:08:46

2

你只能這樣做一個標準的方式:記住touchBegin的觸點並比較touchEnd的點。

2

對於我們這些使用Xamarin:

void panGesture(UIPanGestureRecognizer gestureRecognizer) { 
    if (gestureRecognizer.State == UIGestureRecognizerState.Began) { 
     startLocation = gestureRecognizer.TranslationInView (view) 
    } else if (gestureRecognizer.State == UIGestureRecognizerState.Ended) { 
     PointF stopLocation = gestureRecognizer.TranslationInView (view); 
     float dX = stopLocation.X - startLocation.X; 
     float dY = stopLocation.Y - startLocation.Y; 
     float distance = Math.Sqrt(dX * dX + dY * dY); 
     System.Console.WriteLine("Distance: {0}", distance); 
    } 
} 
13

在斯威夫特

override func viewDidLoad() { 
    super.viewDidLoad() 

    // add your pan recognizer to your desired view 
    let panRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panedView:")) 
    self.view.addGestureRecognizer(panRecognizer) 

} 

func panedView(sender:UIPanGestureRecognizer){ 
    if (sender.state == UIGestureRecognizerState.Began) { 
     startLocation = sender.locationInView(self.view); 
    } 
    else if (sender.state == UIGestureRecognizerState.Ended) { 
     let stopLocation = sender.locationInView(self.view); 
     let dx = stopLocation.x - startLocation.x; 
     let dy = stopLocation.y - startLocation.y; 
     let distance = sqrt(dx*dx + dy*dy); 
     NSLog("Distance: %f", distance); 

     if distance > 400 { 
      //do what you want to do 

     } 

    } 

} 

希望幫助你斯威夫特先驅

0
func swipeAction(gesture: UIPanGestureRecognizer) { 
    let transition = sqrt(pow(gesture.translation(in: view).x, 2) 
        + pow(gesture.translation(in: view).y, 2)) 
}