Skip to content

Instantly share code, notes, and snippets.

@dagronf
Last active August 9, 2019 08:16
Show Gist options
  • Save dagronf/9c3c30d4225338cb9744b409f35cff1c to your computer and use it in GitHub Desktop.
Save dagronf/9c3c30d4225338cb9744b409f35cff1c to your computer and use it in GitHub Desktop.
A swift pan gestureRecognizer that can discriminate in a particular direction. Useful for views requiring (for example) horizontal pan support nested inside a uiscrollview (for example)
//
// DSFRestrictedPanGestureRecognizer.swift
// Time Zones
//
// Created by Darren Ford on 30/6/18.
// Copyright © 2018 Darren Ford. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
class DSFRestrictedPanGestureRecognizer: UIPanGestureRecognizer {
let kDirectionPanThreshold: CGFloat = 2.0;
public enum RestrictTo {
case vertical
case horizontal
}
var _drag: Bool = false
var _moveX: CGFloat = 0
var _moveY: CGFloat = 0
public var direction: RestrictTo = .vertical
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if self.state == .failed {
return
}
guard let touch = touches.first else {
return
}
let nowPoint = touch.location(in: self.view!)
let prevPoint = touch.previousLocation(in: self.view!)
_moveX = prevPoint.x - nowPoint.x
_moveY = prevPoint.y - nowPoint.y
if !_drag {
if fabs(_moveX) > kDirectionPanThreshold {
if self.direction == .vertical {
self.state = .failed
}
else {
_drag = true
}
}
else if fabs(_moveY) > kDirectionPanThreshold {
if self.direction == .horizontal {
self.state = .failed
}
else {
_drag = true
}
}
}
}
override func reset() {
super.reset()
_drag = false
_moveX = 0
_moveY = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment