Created
November 18, 2021 15:52
-
-
Save Tulakshana/ba057339b3e458325e66997a8368dc73 to your computer and use it in GitHub Desktop.
A sub class of UIView with delegate methods to detect pan gestures with direction and displacement.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
protocol TouchDetectingViewDelegate: NSObjectProtocol { | |
func touchDetectingViewDidDetectPan(view: TouchDetectingView, | |
direction: TouchDetectingView.Direction, | |
displacement: CGFloat, | |
state: UIGestureRecognizer.State) | |
func touchDetectingViewPanEnded(view: TouchDetectingView) | |
} | |
class TouchDetectingView: UIView { | |
enum Direction { | |
case up | |
case down | |
case left | |
case right | |
} | |
weak var delegate: TouchDetectingViewDelegate? | |
// MARK: - Lifecycle | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
addGestures() | |
} | |
// MARK: - | |
private func addGestures() { | |
let panGesture = UIPanGestureRecognizer(target: self, | |
action: #selector(didPan(_:))) | |
addGestureRecognizer(panGesture) | |
} | |
@objc private func didPan(_ gestureRecognizer: UIPanGestureRecognizer) { | |
if gestureRecognizer.state != .ended { | |
let translation = gestureRecognizer.translation(in: self) | |
if translation.x.magnitude > translation.y.magnitude { | |
// Horizontal pan | |
if translation.x > 0 { | |
delegate?.touchDetectingViewDidDetectPan(view: self, | |
direction: .right, | |
displacement: translation.x, | |
state: gestureRecognizer.state) | |
} else if translation.x < 0 { | |
delegate?.touchDetectingViewDidDetectPan(view: self, | |
direction: .left, | |
displacement: translation.x, | |
state: gestureRecognizer.state) | |
} | |
} else { | |
// Virtical pan | |
if translation.y > 0 { | |
delegate?.touchDetectingViewDidDetectPan(view: self, | |
direction: .down, | |
displacement: translation.y, | |
state: gestureRecognizer.state) | |
} else if translation.y < 0 { | |
delegate?.touchDetectingViewDidDetectPan(view: self, | |
direction: .up, | |
displacement: translation.y, | |
state: gestureRecognizer.state) | |
} | |
} | |
} else { | |
delegate?.touchDetectingViewPanEnded(view: self) | |
} | |
gestureRecognizer.setTranslation(CGPoint(x: 0, y: 0), in: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment