0

I have a view with a UITapGestureRecognizer instance assigned to it. It correctly responds when the user taps once, but I'd like to prevent it from recognizing again if the user taps again within a short period of time.

I'm using this in a game where the user taps on locations to find hidden objects. I'm trying to prevent the "tap like crazy all over the screen" strategy from working.

Is there a simple solution to this?

Hilton Campbell
  • 6,065
  • 3
  • 47
  • 79

2 Answers2

1

Use a timer to determine whether to accept the tap or not.

Create a BOOL ivar named something like denyTap. Also add an NSTimer ivar named tapTimer.

Then in your tap recognizer method you do something like:

- (void)tapHandler:(UITapGestureRecognizer *)gesture {
    if (!denyTap) {
        dentTap = YES;

        // process the tap as needed

        // Now setup timer - choose a desired interval
        tapTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tapTimer:) userInfo:nil repeats:NO];
    }
}

- (void)tapTimer:(NSTimer *)timer {
    denyTap = NO;
    tapTimer = nil;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

I would not recommend using an NSTimer for resolutions less than 1 second. Plus, it has more overhead. Read this answer for more information on NSTimer vs CACurrentMediaTime().

- (IBAction)handleTap:(UITapGestureRecognizer *)tgr {
     static NSTimeInterval previousTapTime = 0.0; // Or an ivar

     if ((CACurrentMediaTime() - previousTapTime) > 1.0) {
         // A valid tap was detected, handle it
     }

     previousTapTime = CACurrentMediaTime();
}
Community
  • 1
  • 1
duci9y
  • 4,128
  • 3
  • 26
  • 42