【问题标题】:iOS - UITapGestureRecognizer - Selector with ArgumentsiOS - UITapGestureRecognizer - 带参数的选择器
【发布时间】:2012-04-15 04:10:19
【问题描述】:

在我的应用程序中,我在运行时动态地将图像添加到我的视图中。我可以同时在屏幕上显示多个图像。每个图像都是从一个对象加载的。我在图像中添加了一个 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 或任何其他我可以处理它的方法?

谢谢

布赖恩

【问题讨论】:

    标签: ios iphone selector uitapgesturerecognizer


    【解决方案1】:

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

    - (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];
    }
    

    【讨论】:

    • 太棒了。太感谢了。它工作得很好!很好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多