我如何知道在使用UIGestureRecognizers时在哪个子视图上发生了事件?
根据文档:
手势识别器对经过测试的特定视图及其所有子视图的触摸进行操作。
据我所知,“视图”属性是
手势识别器所附的视图。
这将是父视图。
Answers:
这将在事件的位置找到最里面的后代视图。(请注意,如果该子视图具有任何交互式内部私有孙代,则此代码也将找到它们。)
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?`
hitTest:withEvent:
它将尽可能多地落在儿童树上。如果要忽略任何子视图或子视图的子视图,则可以userInteractionEnabled = NO
在这些视图上进行设置。
.superview
迭代找到直到到达原始位置view
。
对于将来的用户...当世界不再使用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;
}