Skip to content

Instantly share code, notes, and snippets.

@wata
Last active April 16, 2020 09:02
Show Gist options
  • Save wata/12e4c604f813bead9823534a10762ec2 to your computer and use it in GitHub Desktop.
Save wata/12e4c604f813bead9823534a10762ec2 to your computer and use it in GitHub Desktop.
enum PanAxis {
case none
case horizontal
case vertical
}
/// Returns only translation in either horizontal or vertical direction determined at `UIGestureRecognizer.State.began`.
class DirectionalPanGestureRecognizer: UIPanGestureRecognizer {
var axis = PanAxis.none
var directionalTranslation: CGPoint {
let translation = self.translation(in: view)
switch axis {
case .horizontal:
return CGPoint(x: translation.x, y: 0)
case .vertical:
return CGPoint(x: 0, y: translation.y)
case .none:
return .zero
}
}
var directionalVelocity: CGPoint {
let velocity = self.velocity(in: view)
switch axis {
case .horizontal:
return CGPoint(x: velocity.x, y: 0)
case .vertical:
return CGPoint(x: 0, y: velocity.y)
case .none:
return .zero
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
guard let view = self.view else { return }
if state == .began {
let velocity = self.velocity(in: view)
axis = abs(velocity.x) > abs(velocity.y) ? .horizontal : .vertical
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment