Max Max - 4 months ago 18
iOS Question

UITapGestureRecognizer for detecting which UIView was tapped on my scree

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
}
}

Answer

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");
    }
}
Comments