通常给UIImageView添加响应按如下方法:
UIImageView *newView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, IMG_WIDTH, IMG_HEIGHT)]; newView.userInteractionEnabled = YES; newView.tag = i; UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TakePhotoFor:)]; [newView addGestureRecognizer:singleTap]; [singleTap release]; //加载已经拍摄的图片 [newView setImage:[UIImage imageNamed:@"MPV.png"]]; [self.view addSubview:newView]; [newView release];
但是今天我在一个循环里创建N个UIImageView,然后在循环外创建的UITapGestureRecognizer,结果点击后就没响应。后来查资料发现Gesture recognizers can be associated to a single view only。也就是要在循环内为每个UIImageView创建并添加UITapGestureRecognizer。
like this:
for (i = 0; i<18; i++) { x = StartX + (i%6)*OFFSET_X; y = StartY + (i/6)*OFFSET_Y; UIImageView *newView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, IMG_WIDTH, IMG_HEIGHT)]; newView.userInteractionEnabled = YES; newView.tag = i; UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TakePhotoFor:)]; [newView addGestureRecognizer:singleTap]; [singleTap release]; //加载已经拍摄的图片 [newView setImage:[UIImage imageNamed:@"MPV.png"]]; [self.view addSubview:newView]; [newView release]; }
问题解决。