I have defined longPress and Pan gesture recognizers at viewController class level as below:
var touch = UILongPressGestureRecognizer()
var pan = UIPanGestureRecognizer()
Then I create a simple UIView:
let qBox = UIView()
qBox.frame = CGRect(x: 100, y: 200, width: 50, height: 50)
self.view.addSubview(qBox)
Then I configure and add my recognizers:
touch.addTarget(self, action: "ourTouched:")
touch.minimumPressDuration = 0
touch.numberOfTouchesRequired = 1
touch.numberOfTapsRequired = 0
qBox.addGestureRecognizer(touch)
pan.addTarget(self, action:"pan:")
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
self.view.addGestureRecognizer(pan)
Now, when I touch the qBox UIView, it triggers "ourTouched" method but if I keep holding and then start panning, it will not drag the qBox UIView. I have tried adding below line in my "ourTouched" function to remove the long press recognizer as soon as user touches the qBox UIView:
qBox.removeGestureRecognizer(touch)
But still, on first touch and drag, only long press method is called. I have to let go and then start again to pan. What am I missing?
The UIPanGestureRecognizer class makes detecting pan gestures fairly straightforward. The heavy lifting is handled by UIPanGestureRecognizer and its superclass, UIGestureRecognizer. In this post, I show you how to use a pan gesture recognizer in Swift.
But somehow swipe is not being triggered (pan is triggered instead) Pan is recognized by the above sequence instead. If pan is commented, swipe is recognized by the same gesture .. With this, 2 questions: What is the difference then between a pan and a swipe? How can one simulate a swipe on iPhone simulator? Show activity on this post.
Most likely, your pan recognizer "wins" the conflict because its gesture is simpler / more general: A swipe is a pan but a pan may not be a swipe, so the pan recognizes first and excludes other recognizers.
SWIFT is a global member-owned cooperative and the world’s leading provider of secure financial messaging services.
Add a UIGestureRecognizerDelegate
to your recognizers and have it return YES
on shouldRecognizeSimultaneously
.
{
// setup ...
touch.delegate = self
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return (gestureRecognizer == touch && otherGestureRecognizer == pan)
}
Update: Swift 4 or later
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return (gestureRecognizer == touch && otherGestureRecognizer == pan)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With