简体   繁体   English

iOS - UITapGestureRecognizer - 带参数的选择器

[英]iOS - UITapGestureRecognizer - Selector with Arguments

In my app I am dynamically adding images to my view at runtime. 在我的应用中,我在运行时动态地将图像添加到我的视图中。 I can have multiple images on screen at the same time. 我可以同时在屏幕上显示多个图像。 Each image is loaded from an object. 每个图像都是从一个对象加载的。 I have added a tapGestureRecongnizer to the image so that the appropriate method is called when I tap it. 我在图像中添加了一个tapGestureRecongnizer,以便在点击它时调用相应的方法。

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

My problem is that I don't know what image I have tapped. 我的问题是我不知道我拍了什么图像。 I know I can call tapGestureRecognizer.location to get the location on screen but thats not really much good to me. 我知道我可以调用tapGestureRecognizer.location来获取屏幕上的位置,但这对我来说并不是很好。 Ideally, I'd like to be able to pass the object that the image was loaded from into the tap gesture. 理想情况下,我希望能够将加载图像的对象传递到点击手势。 However, it seems that I am only able to pass in the selector name "imageTapped:" and not its arguments. 但是,似乎我只能传递选择器名称“imageTapped:”而不是它的参数。

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

Does anyone know of a way that I can pass my object as an argument into the tapGestureRecongnizer or any other way I can get a handle on it? 有没有人知道我可以将我的对象作为参数传递给tapGestureRecongnizer的方式或者我可以处理它的任何其他方式?

Thanks 谢谢

Brian 布赖恩

You're almost there. 你快到了。 UIGestureRecognizer has a view property. UIGestureRecognizer具有视图属性。 If you allocate and attach a gesture recognizer to each image view - just as it appears you do in the code snippet - then your gesture code (on the target) can look like this: 如果您为每个图像视图分配并附加手势识别器 - 就像您在代码片段中看到的那样 - 那么您的手势代码(在目标上)可能如下所示:

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

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

What's less clear from the code you provided is how you associate your Plant model object with it's corresponding imageView, but it could be something like this: 从您提供的代码中可以清楚地看出,如何将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];
}

Now the gr code can do this: 现在gr代码可以这样做:

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

  UIImageView *theTappedImageView = (UIImageView *)gr.view;
  NSInteger tag = theTappedImageView.tag;
  Plant *myPlant = [myPlants objectAtIndex:tag-32];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM