简体   繁体   中英

Passing Arguments with Tap Gesture Recognizer

This question had been asked in some form before, but I could not find an answer that would be applicable to my situation.

In a nutshell: I am building a gallery module for my application. It consist of several sections, with a number of thumbnail images in each section. The basic principle is that an image viewer module gets initiated and presented modally based on what section the user is in and which thumbnail he or she taps on. Seems very simple; all I need is to pass two int variables (one for the section and one for the image) upon initialization of the image viewer, and everything is hunky-dory.

The problem is that UITapGestureRecognizer cannot call a method directly. It uses selectors, through which I am unable to pass an argument, let alone two. What I am looking for is something like this:

[thumbnail004 setUserInteractionEnabled:YES];
UITapGestureRecognizer *tap004 = [[UITapGestureRecognizer alloc] 
                       initWithTarget:self
                       action:@selector(imageTappedWithSectionNumber:6
                                                      andImageNumber:4)];
[thumbnail004 addGestureRecognizer:tap004];

Is there a way to call a method directly with arguments when using UITapGestureRecognizer?

If not, one obvious way to solve this problem would be to create separate methods for each image tap, like:

- (void) image1_1Tapped { 
  // View initialization by passing 1 and 1
  }
- (void) image1_2Tapped { 
  // View initialization by passing 1 and 2
  }
And so on...

This would be possible because the image library is not dynamic, however, it would be the ugliest code in the world, and I would like to avoid it at any cost.

There must be a way to do this with a clean and elegant code...!

For further reference: 1. I do not use IB; I do everything programmatically. 2. Passing one argument is not enough; I really need to pass two.

Use associated object to pass argument along with tap gesture instance.

Refer objective-c-associated-objects link.

A gesture recognizer will only pass one argument into an action selector: itself. I assume you're trying to distinguish between taps on various image subviews of a main view? In that case, your best bet is to call -locationInView:, passing the superview, and then calling -hitTest:withEvent: on that view with the resulting CGPoint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM