UISwipeGestureRecognizer Swipe length

后端 未结 6 2177
暗喜
暗喜 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:15

    I have an implementation similar to the answer in swift that discriminates between a drag and a swipe calculating the distance relative to the container and the speed of the swipe.

    @objc private func handleSwipe(sender: UIPanGestureRecognizer) {
        if (sender.state == .began) {
            self.swipeStart.location = sender.location(in: self)
            self.swipeStart.time = Date()
        }
        else if (sender.state == .ended) {
            let swipeStopLocation : CGPoint = sender.location(in: self)
            let dx : CGFloat = swipeStopLocation.x - swipeStart.location.x
            let dy : CGFloat = swipeStopLocation.y - swipeStart.location.y
            let distance : CGFloat = sqrt(dx*dx + dy*dy );
            let speed : CGFloat = distance / CGFloat(Date().timeIntervalSince(self.swipeStart.time))
            let portraitWidth = min(self.frame.size.width, self.frame.size.height)
            print("Distance: \(distance), speed: \(speed), dy: \(dy), dx: \(dx), portraitWidth: \(portraitWidth), c1: \(distance >  portraitWidth * 0.4), c2: \(abs(dy) < abs(dx) * 0.25), c3: \(speed > portraitWidth * 3.0) ")
            if distance >  portraitWidth * 0.4 && abs(dy) < abs(dx) * 0.25 && speed > portraitWidth * 3.0 {
                if dx > 0 {
                    delegate?.previousAssetPressed(self)
                }else{
                    delegate?.nextAssetPressed(self)
                }
            }
        }
    }
    

提交回复
热议问题