2012-11-26 50 views
4

我有一个水平滚动视图,里面填充了UIImageViews在UIScrollView里面检测UIImageView的水龙头

我想检测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]; 
} 
+0

已经取代<用(小于),因为该代码之后消失。 – Pip

+0

UITapGestureRecognizer的目标应该是自己的,而不是UIImageView本身。 –

回答

12

用户交互为UIImageView设置为NO默认情况下,所以你需要将其设置为YES。 您将其设置为“是”,但不适用于contentOfScrollView

+0

听起来就是这样。但现在我得到 - [UIImageView imageTapped:]:无法识别的选择发送到实例 – Pip

+0

哦,我曾尝试initWithTarget:项目尝试的东西,但我需要将它设置为自我。现在它可以工作。谢谢! – Pip

+0

谢谢你的洞察!我已经阅读了关于用户交互功能的内容,并认为我已经将它完全应用于图像视图的级别以及scrollview的级别。但是我完全忽略了视图下方和scrollview上方的中间层! – Pip

1

你的错误是在这里:

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

您需要将目标更改为“自我”,而不是“商品”,那么就不会崩溃。

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

谢谢。但是,正如你所看到的,我已经自己发现了这一点。 – Pip

相关问题