Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITapGestureRecognizer initWithTarget:action: method to take arguments?

I'm using UITapGestureRecognizer because I'm using a UIScrollView that acts as a container for my UILabels. Basically I'm trying to use an action method with arguments so I can e.g. send myLabel.tag value to the action method to know what action to take depending on what UILabel has has been triggered by a tap.

One way of doing it is having as many action methods as UILabels but that isn't very "pretty" codewise. What I would like to achieve is just having one action method with switch statements.

Is this possible or will I have to do it like this (sigh):

UITapGestureRecognizer *myLabel1Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel1Tap)];
[myLabel1Tap addGestureRecognizer:myLabel1Tap];

UITapGestureRecognizer *myLabel2Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel2Tap)];
[myLabel1Tap addGestureRecognizer:myLabel2Tap];

UITapGestureRecognizer *myLabelNTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabelNTap)];
[myLabel1Tap addGestureRecognizer:myLabelNTap];

- (void)myLabel1Tap {
// Perform action
}

- (void)myLabel2Tap {
// Perform action
}

- (void)myLabelNTap {
// Perform action
}
like image 737
Peter Warbo Avatar asked Jul 08 '11 22:07

Peter Warbo


2 Answers

Add a single gesture recognizer to the view that is the superview of your various labels:

UITapGestureRecognizer *myLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabelTapHandler:)];
[myLabelParent addGestureRecognizer:myLabelTap];

Then when you handle the gesture, determine which label was tapped:

-(void)myLabelTapHandler:(UIGestureRecognizer *)gestureRecognizer {
    UIView *tappedView = [gestureRecognizer.view hitTest:[gestureRecognizer locationInView:gestureRecognizer.view] withEvent:nil];

    // do something with it
}
like image 173
highlycaffeinated Avatar answered Oct 21 '22 06:10

highlycaffeinated


You can use just one UITapGestureRecognizer and in your gesture handler (your myLaberXTap), which has the syntax:

 - (void)handleGesture:(UITapGestureRecognizer*)gestureRecognizer {
     ...
 } 

use gesture.view to know which view you are working on.

like image 24
sergio Avatar answered Oct 21 '22 06:10

sergio