我正在使用UITapGestureRecognizer来检测在我的屏幕上点击了哪个UIView但由于某种原因它只检测父视图点击,例如在代码日志下面只有父视图标记。如何检测主视图中存在的子视图点击。请建议。
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
}
}
答案 0 :(得分:2)
我们有更多选项可以通过点击手势
找到子视图上的检测选择1 :直接点击SubView
cur.execute("INSERT INTO map VALUES (\"" + name + "\"," + repr(item_id) + "," + repr(parent_ID) + ")")
选择2 :通过父视图点击子视图
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapSubView)];
tapGesture.numberOfTapsRequired = 1;
[subView addGestureRecognizer:tapGesture];
印刷输出
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapSubView)];
tapGesture.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapGesture];
-(void)tapSubView:(UITapGestureRecognizer *)sender
{
UIView* view = sender.view;
CGPoint loc = [sender locationInView:view];
UIView* subview = [view hitTest:loc withEvent:nil];
//OR
CGPoint point = [sender locationInView:sender.view];
UIView *viewTouched = [sender.view hitTest:point withEvent:nil];
if ([viewTouched isKindOfClass:[self.view class]])
{
NSLog(@"the subView is called");
}
else
{
NSLog(@"the subView is not called");
}
}
选择3 :使用手势的委托方法查找分路检测
首先你必须添加 GestureRecognizerDelegate
the subView is called
答案 1 :(得分:1)
手势识别器仅与一个特定视图相关联,这意味着它只会识别添加到其中的视图上的触摸。如果您想知道哪个子视图被触及,那么您需要做几件事:
userInteractionEnabled = false
。这将使子视图上的每次触摸都传递到父视图,并且手势识别器将识别触摸。您的视图层次结构或布局上没有足够的信息来确切知道如何从此处继续,但您可以使用这些方法中的一个或一些来确定触摸了哪个视图:UIView.hitTest(_:with:)
, UIView.point(inside:with:)
,CGRectContainsPoint()
或UIGestureRecognizer.location(in:)
。例如,如果子视图彼此不重叠,您可以使用以下代码段来测试触摸是否在特定视图中:
let location = tapGesture.locationInView(parentView)
if CGRectContainsPoint(subview1, location) {
// subview1 was touched
}