2011-01-28 85 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)) 
}