iOS - UITapGestureRecognizer - Selector with Arguments

后端 未结 1 1008
轮回少年
轮回少年 2020-12-31 05:20

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 ta

相关标签:
1条回答
  • 2020-12-31 06:05

    You're almost there. UIGestureRecognizer has a view property. 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:

    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:

    - (void) imageTapped:(UITapGestureRecognizer *)gr {
    
      UIImageView *theTappedImageView = (UIImageView *)gr.view;
      NSInteger tag = theTappedImageView.tag;
      Plant *myPlant = [myPlants objectAtIndex:tag-32];
    }
    
    0 讨论(0)
提交回复
热议问题