Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect tap on UIImageView inside UIScrollView

I have a horizontal scrollview filled with UIImageViews.

I want to detect a tap on the UIImageView and have its background color changed.

Somehow the tap gesture is not working or so.

However, when I add a tap gesture to the scrollview, it works. The scrollview.background color can be changed.

But I want to detect a tap on the UIImageViews it contains!

UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, 768, 127)];
[scrollView setScrollEnabled:YES];
scrollView.backgroundColor = [UIColor orangeColor];
[scrollView setShowsHorizontalScrollIndicator:NO];
UIImageView *contentOfScrollView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 1, 1130, 125)];
scrollView.contentSize = CGSizeMake(contentOfScrollView.frame.size.width, contentOfScrollView.frame.size.height);

for (int aantal=0; aantal < 6; aantal++) {
    UIImageView *item = [[UIImageView alloc] initWithFrame:CGRectMake(3+(aantal*188), 0, 185, 125)];
    item.backgroundColor = [UIColor yellowColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:item action:@selector(imageTapped:)];
    tap.numberOfTapsRequired = 1;
    tap.cancelsTouchesInView=YES;
    item.userInteractionEnabled = YES;
    [item addGestureRecognizer:tap];
    [contentOfScrollView addSubview:item];
}

//UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
//[scrollView addGestureRecognizer:tap];
scrollView.userInteractionEnabled=YES;
scrollView.delaysContentTouches=NO;
[scrollView addSubview:contentOfScrollView];
[self.view addSubview:scrollView];

And this is the imageTapped function.

-(void)imageTapped:(UITapGestureRecognizer *)gesture
{
    NSLog(@"tapped!");
    gesture.view.backgroundColor = [UIColor whiteColor];
}
like image 988
Pip Avatar asked Nov 26 '12 02:11

Pip


1 Answers

User interaction is set to NO by default for UIImageView, so you need to set it to YES. You set it to yes for "item", but not for contentOfScrollView.

like image 199
rdelmar Avatar answered Oct 14 '22 00:10

rdelmar