Interfector
Interfector

Reputation: 1898

Handle several Tap events

I have an UIView which has an UITapGestureRecognizer attached to it that I use to hide the keyboard when the user taps outside the UITextFields. Now, I also have some labels that when tapped show an UIPickerView. The labels use an UITapGestureRecognizer as well. The problem is that the events seem to canibalise themselves.

Is it possible to execute both event handlers when tapping on my labels?

Thank you.

UITapGestureRecognizer* tapForUnit = [[UITapGestureRecognizer alloc] initWithTarget:self.fridgeItemUnit action:@selector(onTap)];
[self.fridgeItemUnit addGestureRecognizer:tapForUnit];

The above code is for one of the labels. I have removed the code for the view because my labels would stop working, but it's exactly the same, only thing different is that it is attached to self.view and the function that is executed is this one:

-(void)dismissKeyboard:(UIGestureRecognizer*)gesture {
    [self.fridgeItemName resignFirstResponder];
    [self.fridgeItemQuantity resignFirstResponder];
}

Upvotes: 0

Views: 131

Answers (1)

atxe
atxe

Reputation: 5079

I would implement the following method from UIGestureRecognizerDelegate:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

I attach an example:

Screenshot

The only thing I did on the XIB was to enabled the user interaction. An here is the .m of the UIViewController:

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    _viewRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTap:)];
    [_viewRecognizer setDelegate:self];
    _labelRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap:)];
    [_labelRecognizer setDelegate:self];
    [self.view addGestureRecognizer:_viewRecognizer];
    [self.label addGestureRecognizer:_labelRecognizer];
}

- (void)viewDidUnload {

    [super viewDidUnload];
    [_viewRecognizer release]; _viewRecognizer = nil;
    [_labelRecognizer release]; _labelRecognizer = nil;
    self.label = nil;
}

- (void)dealloc {
    [_viewRecognizer release];
    [_labelRecognizer release];
    self.label = nil;
    [super dealloc];
}

- (void)labelTap:(UIGestureRecognizer *)recognizer {

    NSLog(@"labelTap");
}

- (void)viewTap:(UIGestureRecognizer *)recognizer {

    NSLog(@"viewTap");
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    NSLog(@"shouldRecognizeSimultaneouslyWithGestureRecognizer");
    return YES;
}

Then when tapping on the label I get the following log:

shouldRecognizeSimultaneouslyWithGestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer
labelTap
viewTap

And when tapping on the view:

viewTap

Upvotes: 2

Related Questions