'When to fetch velocity in UIPanGestureRecognizer
I'm trying to get information about a gesture on main view. My main goal is to fetch start position, end position and velocity between those two. My code is as below;
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(
UIPanGestureRecognizer.init(target: self, action: #selector(self.gestureListener(recognizer:)))
)
}
@objc func gestureListener(recognizer: UIPanGestureRecognizer) {
var start_x: CGFloat? = nil
var start_y: CGFloat? = nil
var end_x: CGFloat? = nil
var end_y: CGFloat? = nil
var velocity_x: CGFloat? = nil
var velocity_y: CGFloat? = nil
switch recognizer.state {
case .began:
let startLocation = recognizer.location(in: recognizer.view)
start_x = startLocation.x
start_y = startLocation.y
break
case .ended:
let endLocation = recognizer.location(in: recognizer.view)
end_x = endLocation.x
end_y = endLocation.y
let velocity = recognizer.velocity(in: recognizer.view)
velocity_x = velocity.x
velocity_y = velocity.y
break
case .possible:
break
case .changed:
break
case .cancelled:
break
case .failed:
break
@unknown default:
break
}
But i couldn't be sure if it is the right way to fetch velocity (in ended state of GestureRecognizer)
What is the difference if i get velocity out of switch case (meaning before every state). Because i saw examples like that on stackoverflow.
To explain more, what i want to achieve is something like GestureDetector's onFling() method in Android;
private class GestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onSingleTapUp(e: MotionEvent): Boolean {
onClick()
return super.onSingleTapUp(e)
}
override fun onDoubleTap(e: MotionEvent): Boolean {
onDoubleClick()
return super.onDoubleTap(e)
}
override fun onLongPress(e: MotionEvent) {
onLongClick()
super.onLongPress(e)
}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
println(e1.x, e1.y, e2.x, e2.y, velocityX, velocityY)
return false
}
}
Thank you for your replies.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
