Theodoros80
Theodoros80

Reputation: 796

pass value to IBAction

I will be fast. I have 6 images,with 6 gestures attached to them and one IBAction. I want each gesture to pass a parameter to the action so i dont have to write 6 separate actions.Here is my code:

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

Upvotes: 0

Views: 924

Answers (2)

rmaddy
rmaddy

Reputation: 318934

There is no way to pass arbitrary data to the insertChar: method. The sender will be the gesture recognizer. Here's one possible solution:

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

Upvotes: 1

Petar
Petar

Reputation: 2283

You need to somehow link the 'sender' value that you get as parameter in -(IBAction)insertChar:(id)sender with the UIImageViews you create.

The action method will look like this:

-(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

}

Then you can link your view in different ways. One way is to use the tag property.

Upvotes: 0

Related Questions