Fitzy
Fitzy

Reputation: 1889

Sending arguments to gesture recognizer initialization selector?

In my program, I have a UITapGestureRecognizer which I have initialized with initWithTarget: action:. I have passed in a selector to call a method by the name of PlanetTapped: (UIImageView *)aPlanet. This calls the method fine, however I would like to know how to pass arguments into action: like you would with performSelector: withObject. Is this popssible? It would make sense to allow you to send arguments to the UIGestureRecognizer's selector. Any help is appreciated.

Upvotes: 11

Views: 13083

Answers (3)

Mario Hendricks
Mario Hendricks

Reputation: 757

In Swift 3.0, the function signature is as follows (substitute another gesture recognizer class as appropriate in these examples):

func myButtonLongTouch(_ sender: UILongPressGestureRecognizer)

You reference this function when setting up your Gesture Recognizers as follows:

longTouchGesture = UILongPressGestureRecognizer(target: self, action: #selector(myButtonLongTouch(_:)))

Then, to access the view (in my case, a button) that was pressed, use the code:

if let button = sender.view as? UIButton {
    // Your code here
}

Finally, don't forget that this function is called multiple times (typically when the gesture begins and when it ends), so you'll want to check the state, which you can do as follows:

if (sender.state == UIGestureRecognizerState.ended) {
    // Your code here
}

Upvotes: 0

lu yuan
lu yuan

Reputation: 7227

- (void)viewDidLoad
{
UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressOnPhotos:)];
[yourView addGestureRecognizer:longPressRecognizer];
}



- (IBAction)handleLongPressOnPhotos:(UILongPressGestureRecognizer *)sender{
// use "sender.view" to get the "yourView" you have long pressed
}

hope these would help you.

Upvotes: 6

sergio
sergio

Reputation: 69047

The correct signature for the method to call would be:

-(void) PlanetTapped: (UIGestureRecognizer*)gestureRecognizer

then you could access the view that received the gesture by calling:

-(void) PlanetTapped: (UIGestureRecognizer*)gestureRecognizer {

    UIImageView* aPlanet = gestureRecognizer.view;
    ...
}

Indeed, this is what UIGestureRecognizer reference states:

A gesture recognizer has one or more target-action pairs associated with it. If there are multiple target-action pairs, they are discrete, and not cumulative. Recognition of a gesture results in the dispatch of an action message to a target for each of those pairs. The action methods invoked must conform to one of the following signatures:

  • (void)handleGesture;
  • (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;

Upvotes: 13

Related Questions