Created
July 19, 2017 14:49
-
-
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 ™️)
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 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