Reputation: 6095
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?
Upvotes: 0
Views: 169
Reputation: 4168
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();
}
Upvotes: 1
Reputation: 318934
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;
}
Upvotes: 1