我的水平滚动视图中填充了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];
}
答案 0 :(得分:14)
默认情况下,NO
的用户互动设置为UIImageView
,因此您需要将其设置为YES
。
您为“item”设置为yes,但不为contentOfScrollView
设置。
答案 1 :(得分:1)
您的错误在这里:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:item action:@selector(imageTapped:)];
您需要将目标更改为“self”而不是“item”,然后它不会崩溃。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];