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

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

根据文件记载:

手势识别器在 对特定视图进行碰撞测试 以及所有视图的子视图。

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

手势识别器的视图 依附于。

这将是父视图。

38501 次浏览

这将在事件的位置找到最内部的后代视图。(注意,如果这个子视图有任何交互式内部私有子视图,这段代码也会找到它们。)

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

雨燕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 的时候,我有了一个更好的选择。

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