Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass argument to action in UIGestureRecognizer initWithTarget action

I am using the code below

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap)];

- (void) processTap
{
//do something
}

But I need to send a data to processTap function. Is there anyway to do this?

like image 620
mommomonthewind Avatar asked Jun 21 '12 23:06

mommomonthewind


2 Answers

Example:

UIImageView *myPhoto = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"tab-me-plese.png"]];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap:)];

[myPhoto setTag:1]; //set tag value
[myPhoto addGestureRecognizer:tap];
[myPhoto setUserInteractionEnabled:YES];

- (void)processTap:(UIGestureRecognizer *)sender
{
    NSLog(@"tabbed!!");
    NSLog(@"%d", sender.view.tag);    
}
like image 95
Thunderbird Avatar answered Jan 01 '23 10:01

Thunderbird


There's a good answer to a similar question at iOS - UITapGestureRecognizer - Selector with Arguments, but if you want to pass data that you don't want to attach to the view, I recommend creating a second function that has access to the data you need. For example:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(passDataToProcessTap)];

- (void)passDataToProcessTap {
    [self processTapWithArgument:self.infoToPass];
    // Another option is to use a static variable,
    // Or if it's not dynamic data, you can just hard code it
}

- (void) processTapWithArgument:(id)argument {
    //do something
}
like image 24
Yonatan Kogan Avatar answered Jan 01 '23 12:01

Yonatan Kogan