Skip to content

Instantly share code, notes, and snippets.

@myell0w
Created July 19, 2017 14:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save myell0w/efe59501467282d8288bc319a15e2a23 to your computer and use it in GitHub Desktop.
Save myell0w/efe59501467282d8288bc319a15e2a23 to your computer and use it in GitHub Desktop.
A UIGestureRecognizer that fires either on long-press or on a force-touch (3D Touch ™️)
import Foundation
import UIKit
import UIKit.UIGestureRecognizerSubclass
/// A Gesture Recognizer that fires either on long press, or on "3D Touch"
final class MNTLongPressGestureRecognizer: UILongPressGestureRecognizer {
// MARK: - Properties
var triggerWithForceTouch: Bool = true
// MARK: - UIGestureRecognizer
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
self.handleTouches(touches, with: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
self.handleTouches(touches, with: event)
}
}
// MARK: - Private
private extension MNTLongPressGestureRecognizer {
func handleTouches(_ touches: Set<UITouch>, with event: UIEvent) {
guard self.triggerWithForceTouch else { return }
guard self.state == .possible else { return }
guard let traitCollection = self.view?.traitCollection else { return }
guard traitCollection.forceTouchCapability == .available else { return }
guard touches.count == 1 else { return }
let touch = touches.first!
let force = touch.force / touch.maximumPossibleForce
if force >= 1.0 {
self.state = .began
MNTTapticFeedbackGenerator.executePeek()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment