10

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?

SahilS
  • 396
  • 5
  • 7
mommomonthewind
  • 4,390
  • 11
  • 46
  • 74

2 Answers2

30

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);    
}
SahilS
  • 396
  • 5
  • 7
Thunderbird
  • 687
  • 6
  • 16
  • 4
    Welcome to Stack Overflow! Always try to provide an explanation to your code. – Unni Kris Nov 28 '12 at 06:48
  • 1
    If all you need is the `UIView` in which the gesture occurred in, then this is a poorly documented, yet valid answer. Otherwise, you must combine with this response: http://stackoverflow.com/questions/11594610/objective-c-storing-hidden-information-into-a-uiview from @nielsbot – SwiftArchitect May 30 '14 at 12:54
  • This tagging is extremely useful for passing UserData - no need to do messy location calculations... – kfmfe04 Jan 06 '15 at 22:44
3

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
}
Community
  • 1
  • 1
Yonatan Kogan
  • 298
  • 3
  • 7