1

I have a UIView that flips over when long pressed. Works beautifully in the simulator, but in the real world the human finger has tiny movements while pressing. These tiny movements reset the gesture and instantly trigger the gesture ended state.

- (void)viewDidLoad {
...

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didLongPress:)];
    longPress.minimumPressDuration = 0.7;
    [self.view addGestureRecognizer:longPress];
}


- (void)didLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if ( gestureRecognizer.state == UIGestureRecognizerStateBegan )
    {
        [UIView transitionFromView:self.questionCardView toView:self.answerCardView
                          duration:1.0
                           options:UIViewAnimationOptionTransitionFlipFromLeft
                        completion:nil];
    }
    else
    {
        [UIView transitionFromView:self.answerCardView toView:self.questionCardView
                          duration:1.0
                           options:UIViewAnimationOptionTransitionFlipFromRight
                        completion:^(BOOL finished){
                            [self.view addSubview:self.questionCardView];
                            [self.view sendSubviewToBack:self.questionCardView];
                        }];
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user432297
  • 121
  • 1
  • 6

2 Answers2

4

You need to properly check the gesture's state in your gesture recognizer's handler.

Try:

- (void)didLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if ( gestureRecognizer.state == UIGestureRecognizerStateBegan )
    {
        [UIView transitionFromView:self.questionCardView toView:self.answerCardView
                          duration:1.0
                           options:UIViewAnimationOptionTransitionFlipFromLeft
                        completion:nil];
    }
    else if ( gestureRecognizer.state == UIGestureRecognizerStateEnded )
    {
        [UIView transitionFromView:self.answerCardView toView:self.questionCardView
                          duration:1.0
                           options:UIViewAnimationOptionTransitionFlipFromRight
                        completion:^(BOOL finished){
                            [self.view addSubview:self.questionCardView];
                            [self.view sendSubviewToBack:self.questionCardView];
                        }];
    }
}

As you had it, the else block was being called on every little movement in addition to the gesture ending.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

UILongPressGestureRecognizer has an allowableMovement property. This is what you are looking for. It lets the user move their finger by the pixel distance determined by the property without causing the gesture to end. The default value is 10 points. Set it to something larger than 10 in your initialisation.

Benjamin Mayo
  • 6,649
  • 2
  • 26
  • 25