Find which child view was tapped when using UITapGestureRecognizer

前端 未结 2 495
慢半拍i
慢半拍i 2020-12-02 15:07

How do I know on which of the the child views an event occurred when using UIGestureRecognizers?

According to the documentation:

A gesture rec

相关标签:
2条回答
  • 2020-12-02 15:52

    This will find the innermost descendant view at the event's location. (Note that if that child view has any interactive internal private grandchildren this code will find those too.)

    UIView* view = gestureRecognizer.view;
    CGPoint loc = [gestureRecognizer locationInView:view];
    UIView* subview = [view hitTest:loc withEvent:nil];
    

    In Swift 2:

    let view = gestureRecognizer.view
    let loc = gestureRecognizer.locationInView(view)
    let subview = view?.hitTest(loc, withEvent: nil) // note: it is a `UIView?`
    

    In Swift 3:

    let view = gestureRecognizer.view
    let loc = gestureRecognizer.location(in: view)
    let subview = view?.hitTest(loc, with: nil) // note: it is a `UIView?`
    
    0 讨论(0)
  • 2020-12-02 16:03

    For future users... I have got a better option now when world is not using obj-c anymore...

    [sender view]

    use it this way:

    UITapGestureRecognizer * objTapGesture = [self createTapGestureOnView:myTextField];
    
    [objTapGesture addTarget:self action:@selector(displayPickerView:)];
    

    // add these methods

    -(void)displayPickerView:(UITapGestureRecognizer*)sender
    {
        UITextField *textField = (UITextField*)[sender view];
        NSLog(@"tag=  %ld", (long)textField.tag);
    }
    
    -(UITapGestureRecognizer*)createTapGestureOnView:(UIView *)view
    {
        view.userInteractionEnabled = YES;
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]init];
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.numberOfTouchesRequired = 1;
        [view addGestureRecognizer:tapGesture];
        return tapGesture;
    }
    
    0 讨论(0)
提交回复
热议问题