使用UITapGestureRecognizer时,可以查找哪个子视图被点击

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

根据文件:

一个手势识别器通过触摸来testing一个特定的视图和所有视图的子视图。

据我所知,“视图”属性是

手势识别器所附的视图。

这将是父视图。

这将在事件的位置find最内层的后代视图。 (请注意,如果该子视图具有任何交互式内部私人孙子,则此代码也会find这些内容。)

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?` 

对于未来的用户…当世界不再使用obj-c时,我已经有了一个更好的select…

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