Ios 将值传递给iAction

Ios 将值传递给iAction,ios,uitapgesturerecognizer,Ios,Uitapgesturerecognizer,我会很快的。 我有6张图片,6个手势和一个IBAction。我希望每个手势向动作传递一个参数,这样我就不必编写6个单独的动作。下面是我的代码: oneImage =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"one.gif"]]; two Image=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"two.gif"]]; +4 more im

我会很快的。 我有6张图片,6个手势和一个IBAction。我希望每个手势向动作传递一个参数,这样我就不必编写6个单独的动作。下面是我的代码:

    oneImage =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"one.gif"]];
    two Image=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"two.gif"]];
    +4 more images

     UITapGestureRecognizer *oneGest=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(insertChar:)];
         UITapGestureRecognizer *twoGest=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(insertChar:)];
    +4 more gestures


    -(IBAction)insertChar:(id)sender
    {

    textfield.text = [textfield.text stringByAppendingString:@" PASS HERE VALUE FROM GESTURE,"ONE","TWO",etc "];
    }

您需要以某种方式将
-(iAction)insertChar:(id)sender
中作为参数获得的“sender”值与您创建的
UIImageView
链接起来

操作方法如下所示:

-(IBAction)insertChar:(id)sender
{

 UIGestureRecognizer *gestureRecognizer = (UIGestureRecognizer*)sender;
 UIView *view = gestureRecognizer.view;
//do whatever you want with the view that has the gestureRecgonizer's event on

}

然后您可以用不同的方式链接视图。一种方法是使用tag属性。

无法将任意数据传递到
insertChar:
方法。
发送方
将是手势识别器。这里有一个可能的解决方案:

oneImage =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"one.gif"]];
oneImage.tag = 1;
twoImage=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"two.gif"]];
twoImage.tag = 2;
// +4 more images

UITapGestureRecognizer *oneGest=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(insertChar:)];
UITapGestureRecognizer *twoGest=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(insertChar:)];
// +4 more gestures

-(IBAction)insertChar:(UITapGestureRecognizer *)sender {
    static NSString *labels[6] = { @"ONE", @"TWO", ... @"SIX" };
    UIView *view = sender.view;
    NSInteger tag = view.tag;
    NSString *label = labels[tag - 1]; // since tag is 1-based.

    textfield.text = [textfield.text stringByAppendingString:label];
}

发件人是id,可以采用任何形式。或者您可以将其键入
(UITapgestureRecognitizer*)发送方
并使用它。这与Xcode无关。好的H2CO3如果这是一个巨大的错误,那么我深表歉意!:(我打赌搜索
UITapgestureRecognitizer sender
的速度比不上谷歌搜索
UITapgestureRecognitizer sender
,这给了我们一个答案:
insertChar:
发件人将是手势识别器,而不是图像视图。我会尝试并与您联系。效果很好!!非常感谢!我也给出了一个提示:One image.tag应该是0,two image.tag=1等等。最好不要使用0作为标记值,因为这是所有视图的默认值。我更新了答案的代码,以反映
标记是基于1的。