Using UITapGestureRecognizer

New for iPhone dev. I have a view that contains a UIScrollView that contains a UIImageView. I added a (double) gesture recognizer when viewing the image, which opens a warning window. For some reason, and I'm sure I'm just retarded, it opens 3 times.

Here is my code:

- (void)viewDidLoad { scrollView.delegate = self; UIImage* image = imageView.image; imageView.bounds = CGRectMake(0, 0, image.size.width, image.size.height); scrollView.contentSize = image.size; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; tapGesture.numberOfTapsRequired = 2; [imageView addGestureRecognizer:tapGesture]; [tapGesture release]; NSLog(@"LOADED"); [super viewDidLoad]; } -(IBAction) handleTapGesture:(UIGestureRecognizer *) sender { CGPoint tapPoint = [sender locationInView:imageView]; int tapX = (int) tapPoint.x; int tapY = (int) tapPoint.y; NSLog(@"TAPPED X:%d Y:%d", tapX, tapY); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"How are you?" delegate:nil cancelButtonTitle:@"I'm awesome." otherButtonTitles:nil]; [alert show]; [alert release]; } 

I just started iPhone dev a few days ago. This issue reminds me of the problems with event bubbles that I encountered in javascript. Any ideas?

+4
source share
1 answer

Not sure what the exact reason is, but UIAlertView somehow makes the gesture shoot again. The workaround is to perform the show outside of the gesture handler using the performSelector function:

 -(void) handleTapGesture:(UIGestureRecognizer *) sender { CGPoint tapPoint = [sender locationInView:imageView]; int tapX = (int) tapPoint.x; int tapY = (int) tapPoint.y; NSLog(@"TAPPED X:%d Y:%d", tapX, tapY); [self performSelector:@selector(showMessage) withObject:nil afterDelay:0.0]; } - (void)showMessage { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"How are you?" delegate:nil cancelButtonTitle:@"I'm awesome." otherButtonTitles:nil]; [alert show]; [alert release]; } 

Edit:
The sign of gesture recognition passes through different states in the gesture (Start, Changed, etc.), and it calls the handler method every time the state changes. Therefore, the best and probably the right decision is to check the state recognition property of the gesture recognizer at the top of the handler:

 -(void) handleTapGesture:(UIGestureRecognizer *) sender { if (sender.state != UIGestureRecognizerStateEnded) // <--- return; // <--- CGPoint tapPoint = [sender locationInView:imageView]; int tapX = (int) tapPoint.x; int tapY = (int) tapPoint.y; NSLog(@"TAPPED X:%d Y:%d", tapX, tapY); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"How are you?" delegate:nil cancelButtonTitle:@"I'm awesome." otherButtonTitles:nil]; [alert show]; [alert release]; } 
+10
source

All Articles