Skip to content

Instantly share code, notes, and snippets.

@rnystrom
Last active February 3, 2018 22:58
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnystrom/fa23c50b11e84119774e to your computer and use it in GitHub Desktop.
Save rnystrom/fa23c50b11e84119774e to your computer and use it in GitHub Desktop.
RN3DTouchGestureRecognizer
//
// RN3DTouchGestureRecognizer.swift
//
// Created by Ryan Nystrom on 10/10/15.
// Copyright © 2015 Ryan Nystrom. All rights reserved.
//
import UIKit.UIGestureRecognizerSubclass
class RN3DTouchGestureRecognizer: UIGestureRecognizer {
// 0 to 1.0, reaches 1.0 when 3d touch state is active
private(set) var progress: CGFloat = 0
// roughly when "Peek" activates
private let threshold: CGFloat = 0.22
// ignore the first 10% of the touch before enabling 3D
private let delay: CGFloat = 0.1
private var shouldPresent: Bool {
return progress >= 1.0
}
private func handleTouches(touches: Set<UITouch>, failedState: UIGestureRecognizerState, continueState: UIGestureRecognizerState) {
guard let touch = touches.first where touches.count == 1 else {
state = failedState
return
}
let f = max(touch.force - touch.maximumPossibleForce * delay, 0)
let p = f / (touch.maximumPossibleForce * threshold)
progress = min(max(p, 0), 1)
if shouldPresent {
state = .Ended
} else {
state = continueState
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
handleTouches(touches, failedState: .Failed, continueState: .Began)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
handleTouches(touches, failedState: .Cancelled, continueState: .Changed)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
handleTouches(touches, failedState: .Failed, continueState: .Cancelled)
}
override func touchesCancelled(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesCancelled(touches, withEvent: event)
state = .Cancelled
}
override func reset() {
super.reset()
progress = 0
state = .Possible
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment