15

在我的应用程序中,我在运行时动态地将图像添加到我的视图中。我可以同时在屏幕上显示多个图像。每个图像都是从一个对象加载的。我在图像中添加了一个 tapGestureRecongnizer,以便在我点击它时调用适当的方法。

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

我的问题是我不知道我点击了什么图像。我知道我可以调用 tapGestureRecognizer.location 来获取屏幕上的位置,但这对我来说并不是很好。理想情况下,我希望能够将加载图像的对象传递到点击手势中。但是,似乎我只能传入选择器名称“imageTapped:”而不是它的参数。

- (IBAction)imageTapped:(Plant *)plant
{
   [self performSegueWithIdentifier:@"viewPlantDetail" sender:plant];
}

有谁知道我可以将我的对象作为参数传递给 tapGestureRecongnizer 或者我可以处理它的任何其他方式?

谢谢

布赖恩

4

1 回答 1

27

您快到了。UIGestureRecognizer 有一个 view 属性。如果您为每个图像视图分配并附加一个手势识别器 - 就像您在代码片段中所做的那样 - 那么您的手势代码(在目标上)可能如下所示:

- (void) imageTapped:(UITapGestureRecognizer *)gr {

  UIImageView *theTappedImageView = (UIImageView *)gr.view;
}

从您提供的代码中不太清楚的是如何将您的 Plant 模型对象与其对应的 imageView 相关联,但它可能是这样的:

NSArray *myPlants;

for (i=0; i<myPlants.count; i++) {
    Plant *myPlant = [myPlants objectAtIndex:i];
    UIImage *image = [UIImage imageNamed:myPlant.imageName];  // or however you get an image from a plant
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];  // set frame, etc.

    // important bit here...
    imageView.tag = i + 32;

    [self.view addSubview:imageView];
}

现在 gr 代码可以做到这一点:

- (void) imageTapped:(UITapGestureRecognizer *)gr {

  UIImageView *theTappedImageView = (UIImageView *)gr.view;
  NSInteger tag = theTappedImageView.tag;
  Plant *myPlant = [myPlants objectAtIndex:tag-32];
}
于 2012-03-31T23:28:19.597 回答