UISwipeGestureRecognizer Swipe length

后端 未结 6 2185
暗喜
暗喜 2020-12-01 00:53

Any idea if there is a way to get the length of a swipe gesture or the touches so that i can calculate the distance?

6条回答
  •  有刺的猬
    2020-12-01 01:18

    In Swift

     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
            }
        }
    }
    

    Hope that helps all you Swift pioneers

提交回复
热议问题