简体   繁体   中英

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];
}

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 .

Your error is here:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:item action:@selector(imageTapped:)];

You need to change the target to "self" instead of "item", then it won't crash.

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM