查找使用UITapGestureRecognizer时点击了哪个子视图

时间:2010-05-07 13:29:05

标签: objective-c ipad

使用UIGestureRecognizers时,如何知道事件发生在哪个子视图上?

根据文件:

  

手势识别器可以操作   接触到特定视图的测试   以及该视图的所有子视图。

据我所知,'view'属性是

  

手势识别器的视图   附于。

这将是父视图。

2 个答案:

答案 0 :(得分:185)

这将在事件的位置找到最里面的后代视图。 (请注意,如果该子视图具有任何交互式内部私有孙子,则此代码也会找到它们。)

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

在Swift 2中:

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

在Swift 3中:

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

答案 1 :(得分:-1)

对于未来的用户...... 现在,当世界不再使用obj-c时,我有了更好的选择......

[sender view]

以这种方式使用它:

UITapGestureRecognizer * objTapGesture = [self createTapGestureOnView:myTextField];

[objTapGesture addTarget:self action:@selector(displayPickerView:)];

//添加这些方法

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