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


69

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

根据文档:

手势识别器对经过测试的特定视图及其所有子视图的触摸进行操作。

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

手势识别器所附的视图。

这将是父视图。

Answers:


203

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

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

优秀的 !非常感谢-这真的帮助了我!
RPM

太棒了!这将不仅对这种情况有帮助:)
RileyE 2013年

11
只是想补充一点,hitTest:withEvent:它将尽可能多地落在儿童树上。如果要忽略任何子视图或子视图的子视图,则可以userInteractionEnabled = NO在这些视图上进行设置。
robotspacer 2014年

1
如果我们只想降低一级怎么办?
John D.

1
@JohnD。.superview迭代找到直到到达原始位置view
kennytm

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

1
-[UIGestureRecognizer视图]返回其附加的视图(按规格);OP对该视图的子视图感兴趣。
杰森·
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.