Max
Max

Reputation: 5932

UITapGestureRecognizer for detecting which UIView was tapped on my screen

I am using UITapGestureRecognizer for detecting which UIView was tapped on my screen but for some reason it only detects the parent view tap, for example below code logs only parent views tag. How do i detect subview taps which are present on main view. Please suggest.

Inside View did load :- 

UITapGestureRecognizer *viewTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionForViewTapped:)];
    [self.view addGestureRecognizer:viewTapRecognizer];


-(void) actionForViewTapped:(UITapGestureRecognizer*)sender {
    NSLog(@"view tapped");
    UIView *view = sender.view;
    NSLog(@"view tag is %lu", view.tag); //Always prints parent view tag. 

    if(view.tag == 10){
        NSLog(@"tag1 tapped"); // not called
    }
    if(view.tag == 20){
        NSLog(@"tag 2 tapped"); // not called
    }
}

Upvotes: 1

Views: 258

Answers (2)

Bhumit Mehta
Bhumit Mehta

Reputation: 16318

You can detect subview using following code, I just tested creating sample project.

-(void) actionForViewTapped:(UITapGestureRecognizer*)sender {
    NSLog(@"view tapped");
    UIView *view = sender.view;
    CGPoint loc = [sender locationInView:view];
    UIView* subview = [view hitTest:loc withEvent:nil];
    NSLog(@"view tag is %lu", subview.tag); //will print Subview tag.

    if(view.tag == 10){
        NSLog(@"tag1 tapped");  
    }
    if(view.tag == 20){
        NSLog(@"tag 2 tapped");
    }
}

Upvotes: 3

Medo
Medo

Reputation: 63

A UIGestureRecognizer is to be used with a single view.

If you want to use UIGestureRecognizer you will have to create one for each view, calling the same method.

Upvotes: 0

Related Questions