Malloc
Malloc

Reputation: 16276

UITapGestureRecognizer on multiple UIView (scrollview subviews)

I have set a scrollview and a bench of UIView (scrollview subviews) with gestures on them:

  for (id element in array) {

        CustomView *view = [[CustomView alloc] init];
        [view setFrame:CGRectMake(x, 16, self.view.frame.size.width, self.view.frame.size.height)];
        [self.scrollView setContentSize:CGSizeMake(scrollContentSizeWidth, self.scrollView.frame.size.height)];
        UITapGestureRecognizer *tap =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(selectView:)];
        [self.view setTag:[[element valueForKey:@"Id"] integerValue]];
        [self.view addGestureRecognizer:tap];
        view.userInteractionEnabled = YES;
        [self.scrollView addSubview:view];
        scrollContentSizeWidth +=110;
        x += 110;
    }

The called method when a view is touched:

-(void)selectView:(UITapGestureRecognizer *)recognizer{

    NSLog(@"id : %i",recognizer.view.tag);//always last assigned value in the loop above

}

So how to fix that? UITapGestureRecognizer seems to be affected to the last view only.

Upvotes: 0

Views: 607

Answers (1)

Sunny Shah
Sunny Shah

Reputation: 13020

replace this line

[self.view addGestureRecognizer:tap];

with this

 [view addGestureRecognizer:tap];

Upvotes: 2

Related Questions