问题
I want to get the velocity of a pan gesture, and I thought to use the sender's velocity property, but it doesn't seem to work:
@IBAction func handleGesture(sender: AnyObject) {
let v = sender.velocity
}
but it throws an error saying :
"ambiguous use of 'velocity'"
If that's not the way to access the velocity of a pan gesture, what is?
回答1:
UIPanGestureRecognizer does not have property named velocity
. You should use velocityInView
method.
func userPanned(sender: UIPanGestureRecognizer) {
let v = sender.velocityInView(self.view)
}
回答2:
For velocity, you need to do the following
sender.velocityInView(self.view) gives you the pixels. Inorder to get the velocity, you need to divide it by 60 like this:
sender.velocityInView(self.view).x / 60 - For horizontal
sender.velocityInView(self.view).y / 60 - For vertical
Hence, you can update the position just by adding it with your initial value like this:
var initialLocation: CGPoint? -> Global
initialLocation.x = (initialLocation ?? 0)
(initialLocation.x)! = (initialLocation.x)! + (sender.velocity(in: colorSlider!).x / 60) - For horizontal
(initialLocation.y)! = (initialLocation.y)! + (sender.velocity(in: colorSlider!).y / 60) - For vertical
Thanks.
来源:https://stackoverflow.com/questions/26748219/access-the-velocity-of-a-pan-gesture