Skelewu
Skelewu

Reputation: 21

How to pass multiple parameters to a UITapGesture method with selector

Trying to figure out how to pass a string argument to my method which I call using a selector. It also happens to be a method I wrote to respond to a single Tap gesture

My Method looks like this :

-(void)handleSingleTap:(UITapGestureRecognizer *)recognizer Mystring:(NSString *) TheString{
}

I am trying to call the method like this :

UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)];

Right now my call does not include the second NSString parameter I want to pass. How do I pass that second parameter? Thanks you.

Upvotes: 2

Views: 758

Answers (2)

Paresh Navadiya
Paresh Navadiya

Reputation: 38259

Create category for UITapGestureRecognizer to use objc_setAssociatedObject

Add below category :

#import <objc/runtime.h> 

static const void *stringKey = &stringKey;

@implementation UITapGestureRecognizer (string)

- (void)setString:(NSString *)stringToBePassedInGesture
{
   objc_setAssociatedObject(self, stringKey, stringToBePassedInGesture, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)string
{
  return objc_getAssociatedObject(self, stringKey);
}

@end

Use like this:

[singleTapGestureRecognizer setString:yourStringHere];

More reference from here

Upvotes: 1

Matic Oblak
Matic Oblak

Reputation: 16794

I have no idea what language have you come from (if any) but it does not work this way in objective-C. The object you create has a certain scope and can have an owner of sorts. That means if you created an object (your string) in a method viewDidLoad you can only use it in that method unless you assign it to some object (for instance to self using a property as already mentioned). I suggest you try to search the web about creating one of those.

In a situation as yours it would be great if the calling object could store your string as a property which could then be used in a handler method as well. That would mean you would assign the string to the tap gesture gesture.myString = myString and then in the handler you could call recognizer.myString to get this string. This can actually be achieved by subclassing the gesture recognizer and creating that property on it but I would not suggest doing something like that just to get a string passed.

So generally you can not do that the nice way and believe me I do wish it would be possible as this same issue can get extremely difficult is situations such as adding a button to a table view cell. The generic handles are very limited and using more or less anything such as buttons, cells, gesture recognizers you can not expect to get much more info then the sender itself (sometimes even less like an index path).

Upvotes: 0

Related Questions