UISwipeGestureRecognizer滑动长度

Tom*_*omo 36 iphone gesture ipad uigesturerecognizer ios

知道是否有办法获得滑动手势或触摸的长度,以便我可以计算距离?

Mat*_*uch 56

从滑动手势中获取距离是不可能的,因为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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果使用UIPanGestureRecognizer,内置方法 - (CGPoint)translationInView:(UIView*)视图效果很好. (10认同)
  • 你肯定会在这里使用translationInView.也许MB有一天可以编辑答案,因为它是如此高的标记!例如http://stackoverflow.com/questions/15888276/with-uipangesturerecognizer-is-there-a-way-to-only-act-so-often-like-after-xm Rock on ... (2认同)

Col*_*ris 16

在斯威夫特

 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)

}

   @objc func panedView(sender:UIPanGestureRecognizer){
        var startLocation = CGPoint()
        //UIGestureRecognizerState has been renamed to UIGestureRecognizer.State in Swift 4
        if (sender.state == UIGestureRecognizer.State.began) {
            startLocation = sender.location(in: self.view)
        }
        else if (sender.state == UIGestureRecognizer.State.ended) {
            let stopLocation = sender.location(in: 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助所有Swift先锋

  • 对于懒惰的人,你还应该在类中声明 var startLocation = CGPoint() (2认同)