Reputation: 13
From what I already know from this question Detecting the direction of PAN gesture in iOS answered by H2CO3, you can detect left or right movement in UIPanGestureRecognizer
by using:
CGPoint vel = [gesture velocityInView:self.view];
if (vel.x > 0)
{
// user dragged towards the right
}
else
{
// user dragged towards the left
}
I want to detect left or right movement when user tap and hold a button similar to code above by using UILongPressGestureRecognizer
when user entered UIGestureRecognizerStateChanged
state, but it seems I can't simply using velocityInView
to make things work in my case.
Anyone can help me?
Upvotes: 1
Views: 1833
Reputation: 11132
First set the recognizer's allowableMovement
to a big value (it's 10 pixels by default). And use the following code
-(void)longPressed:(UILongPressGestureRecognizer*)g
{
if (g.state == UIGestureRecognizerStateBegan) {
_initial = [g locationInView:self.view]; // _initial is instance var of type CGPoint
}
else if (g.state == UIGestureRecognizerStateChanged)
{
CGPoint p = [g locationInView:self.view];
double dx = p.x - _initial.x;
if (dx > 0) {
NSLog(@"Finger moved to the right");
}
else {
NSLog(@"Finger moved to the left");
}
}
}
Note that UILongPressGestureRecognizer
is continuous, so you'll receive multiples UIGestureRecognizerStateChanged
. Use UIGestureRecognizerStateEnded
if you only want one notification when the user lifted his finger.
Upvotes: 6