It seems that with new iOS versions (10 for me at the moment), the long press recognizer callbacks for both the .begin
and .ended
states happen one after the other, only after the event has ended, that is only when you raise your finger from the screen.
That makes the difference between the two events be fractions of milliseconds, and not what you were actually searching for.
Until this will be fixed, I decided to create another gesture recognizer from scratch in swift, and that would be its working skeleton.
import UIKit.UIGestureRecognizerSubclass
class LongPressDurationGestureRecognizer : UIGestureRecognizer {
private var startTime : Date?
private var _duration = 0.0
public var duration : Double {
get {
return _duration
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
startTime = Date() // now
state = .begin
//state = .possible, if you would like the recongnizer not to fire any callback until it has ended
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
_duration = Date().timeIntervalSince(self.startTime!)
print("duration was \(duration) seconds")
state = .ended
//state = .recognized, if you would like the recongnizer not to fire any callback until it has ended
}
}
Then you can access the .duration
property of the LongPressDurationGestureRecognizer
gesture recognizer easily.
For instance:
func handleLongPressDuration(_ sender: LongPressDurationGestureRecognizer) {
print(sender.duration)
}
This specific example, doesn't take into consideration how many touches actually took place, or their location. But you can easily play with it, extending the LongPressDurationGestureRecognizer.