【问题标题】:Detect tap on UIImageView inside UIScrollView检测对 UIScrollView 内的 UIImageView 的点击
【发布时间】:2012-11-26 02:11:43
【问题描述】:

我有一个水平滚动视图,里面装满了UIImageViews

我想检测对UIImageView 的点击并更改其背景颜色。

不知何故,点击手势不起作用。

但是,当我向滚动视图添加点击手势时,它可以工作。 scrollview.background color 可以更改。

但我想检测对它包含的UIImageViews 的点击!

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

这就是 imageTapped 函数。

-(void)imageTapped:(UITapGestureRecognizer *)gesture
{
    NSLog(@"tapped!");
    gesture.view.backgroundColor = [UIColor whiteColor];
}

【问题讨论】:

  • 已将
  • UITapGestureRecognizer 的目标应该是 self 而不是 UIImageView 本身。

标签: ios uiscrollview uiimageview uitapgesturerecognizer


【解决方案1】:

UIImageView的用户交互默认设置为NO,所以需要设置为YES。 您将“项目”设置为 yes,但对于 contentOfScrollView 则不设置。

【讨论】:

  • 听起来就是这样。但现在我得到-[UIImageView imageTapped:]: unrecognized selector sent to instance
  • 哦,我曾尝试过 initWithTarget:item 来尝试一些东西,但我需要将其设置为 self。现在它起作用了。谢谢!
  • 感谢您的洞察!我已经阅读了有关用户交互功能的信息,并认为我已经在图像视图的级别以及滚动视图的级别上完全应用了它。但我完全忽略了视图下方和滚动视图上方的中间层!
【解决方案2】:

你的错误在这里:

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

您需要将目标更改为“self”而不是“item”,这样它就不会崩溃。

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

【讨论】:

  • 谢谢。但是,如您所见,我自己已经发现了这一点。
猜你喜欢
  • 2018-04-17
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 2019-09-08
  • 1970-01-01
相关资源
最近更新 更多