UITapGestureRecognizer用于检测在我的屏幕上点击了哪个UIView
我正在使用UITapGestureRecognizer
来检测哪个UIView是在我的屏幕上点击,但由于某种原因,它只能检测到父视图点击,例如下面的代码日志只有父视图标记。 如何检测在主视图中存在的子视图水龙头? 请build议。
Inside View did load :- UITapGestureRecognizer *viewTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionForViewTapped:)]; [self.view addGestureRecognizer:viewTapRecognizer]; -(void) actionForViewTapped:(UITapGestureRecognizer*)sender { NSLog(@"view tapped"); UIView *view = sender.view; NSLog(@"view tag is %lu", view.tag); //Always prints parent view tag. if(view.tag == 10){ NSLog(@"tag1 tapped"); // not called } if(view.tag == 20){ NSLog(@"tag 2 tapped"); // not called } }
你可以使用下面的代码检测子视图,我只是testing创build示例项目。
-(void) actionForViewTapped:(UITapGestureRecognizer*)sender { NSLog(@"view tapped"); UIView *view = sender.view; CGPoint loc = [sender locationInView:view]; UIView* subview = [view hitTest:loc withEvent:nil]; NSLog(@"view tag is %lu", subview.tag); //will print Subview tag. if(view.tag == 10){ NSLog(@"tag1 tapped"); } if(view.tag == 20){ NSLog(@"tag 2 tapped"); } }
UIGestureRecognizer
将用于单个视图。
如果你想使用UIGestureRecognizer
你将不得不为每个视图创build一个,调用相同的方法。