2

TapGesture recognizer on multiple UIImageView is not working, while it detects last added imageviews gesture.. I have done this,

 UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myFunction:)];
tapped.numberOfTapsRequired = 1;
tapped.delegate = self;


UIImageView *sample_book1= [[UIImageView alloc]initWithFrame:CGRectMake(70, 135, 100,125) ];
sample_book1.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mathematics.png"]];
sample_book1.userInteractionEnabled = YES;
sample_book1.tag = 0;
[sample_book1 addGestureRecognizer:tapped];
[self.view addSubview:sample_book1];

UIImageView *sample_book2= [[UIImageView alloc]initWithFrame:CGRectMake(220, 135, 100,125) ];
sample_book2.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"biology.png"]];
sample_book2.userInteractionEnabled = YES;
sample_book2.tag = 1;
[sample_book2 addGestureRecognizer:tapped];
[self.view addSubview:sample_book2];

UIImageView *sample_book3= [[UIImageView alloc]initWithFrame:CGRectMake(370, 135, 100,125) ];
sample_book3.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"chemistry.png"]];
sample_book3.userInteractionEnabled = YES;
sample_book3.tag = 2;
 [sample_book3 addGestureRecognizer:tapped];
[self.view addSubview:sample_book3];

The tap gesture is not working in sample_book1,sample_book2.... it's only working in sample_book3.. What i'm doing wrong..

Harish
  • 2,496
  • 4
  • 24
  • 48

2 Answers2

7

What you are doing wrong is trying to use the gesture in a way that it is not supposed to be used. A gesture can only be attached to one view. You need to make a new one for each view.

borrrden
  • 33,256
  • 8
  • 74
  • 109
  • This is the correct answer, just a small addendum: http://stackoverflow.com/questions/4747238/can-you-attach-a-uigesturerecognizer-to-multiple-views – Rui Peres Apr 10 '13 at 08:54
7

As borrrden said, when trying to track gesture, each view must have its own gestureRecognizer. For each of your sample_books, you should use

[sample_bookX addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(myFunction:)]];

instead of trying to add multiple times the same GR

The argument received by myFunction: would then be the proper tapGR and you could get to the tapped imageView by calling sender.view (providing your myFunction signature look like

- (void) myFunction:(UIGestureRecognizer *)sender

Cheers,

Florian Burel
  • 3,408
  • 1
  • 19
  • 20