Access the velocity of a pan gesture

感情迁移 提交于 2020-01-26 03:53:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!