Swift 3
Create the gesture and attach it to your view:
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleGesture))
yourView.addGestureRecognizer(panGesture)
Create a class variable that will hold the value of the latest direction:
var latestDirection: Int = 0
Panning on yourView
will trigger the gesture handler where we check if pan direction was changed:
func handleGesture(gesture: UIPanGestureRecognizer) {
let velocity = gesture.velocity(in: yourView)
var currentDirection: Int = 0
if velocity.x > 0 {
print("panning right")
currentDirection = 1
} else {
print("panning left")
currentDirection = 2
}
// check if direction was changed
if currentDirection != latestDirection {
print("direction was changed")
}
latestDirection = currentDirection
}
This only handles direction change between left and right pan, but if someone wants to detect pan up/down, add this code to handleGesture
function:
if velocity.y > 0 {
print("panning down")
} else {
print("panning up")
}