我在这个网站上得到了这个解决方案:Click an UIImage and open an UIImageView in Objective-c
将UITapGestureRecognizer
添加到您的UIImageView
:
UITapGestureRecognizer *tapRecognizer;
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yourSelector)];
[thumbnail addGestureRecognizer:tapRecognizer];
[tapRecognizer release];
thumbnail.userInteractionEnabled = YES; // very important for UIImageView
这对于单个ImageView非常有效,但我正在向我的scrollView添加多个(大约20个),那么我如何区分哪个ImageView将被用户点击或选择。我尝试设置自己的@ imageView (ImageClicked),但它只返回最后一个选择器的标签。
我在一个循环中添加了addGestureRecognizer,因为我在imageView中动态加载了20个静态图像。
发布于 2012-01-31 15:48:49
这可能会有帮助
for(int i=0;i<20;i++)
{
UIImageView *img=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yourimage.png"]];
[img setTag:i];
img.frame= //set frame accordingly;
img.userInteractionEnabled = YES;
UITapGestureRecognizer *tap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[img addGestureRecognizer:tap];
[tap release];
[scrollView addSubView:img];
}
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
UIImageView *imageView = (UIImageView *)recognizer.view;
switch([imageView tag])
{
case 1:
//do your work
break;
.
.
.
.
case n:
}
}
发布于 2012-01-31 15:16:58
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
for (UIImageView *thumbnail in imageArray) {
[thumbnail addGestureRecognizer:tapRecognizer];
}
[tapRecognizer release];
您可以从UIGestureRecognizer的“视图”属性中获取视图。在您的选择器中,例如:
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
UIImageView *imageView = (UIImageView *)recognizer.view;
// Now do something with your view
}
发布于 2012-01-31 16:06:55
您不能将一个单击识别器添加到多个视图。为要添加点击识别器的每个视图创建一个新视图。由于您使用的是tableview,因此只需在tableView:cellForRowAtIndexPath:
方法中执行此操作:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// usual implementation
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeue ...];
if (!cell) {
cell = [[UITableViewCell alloc] init....];
// add new gesture recognizer here.
}
// setup cell: set the image (just an example)
cell.imageView.image = [images objectAtIndex:indexPath.row];
return cell;
}
而不是像其他答案中提到的那样使用标签,只获取图像视图,尝试与底层模型一起工作。处理tap时,找到indexPath以了解要访问的模型对象:
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
UIImageView *imageView = (UIImageView *)recognizer.view;
// assumes the image view is direct subview of the cell
// change to match your cell structure
UITableViewCell *cell = (UITableViewCell *) [imageView superview];
// get the index path for the cell clicked
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
// TODO: Use index path to get full image to display
}
通过这种方式,您可以知道所单击图像的确切行,因此您可以访问您的模型以访问要显示的完整图像。
https://stackoverflow.com/questions/9075738
复制相似问题