7

我在 iOS 应用程序上的事件响应者链遇到问题。

问题如下,我在一个更大的视图(正方形)上有一组子视图(气泡),如果我点击按钮,我希望能够显示某个视图,但是如果我点击其他任何我想要的地方查看隐藏。

问题是当我点击气泡时,两个视图(子视图和父视图)都在触发,我该如何防止这种情况发生?

如果孩子已经对触摸事件采取了行动,那不应该是它的结束吗?

我的 Bubbles 正在使用 UITapGestureRecognizer 识别 Tap 手势,而父视图(正方形)使用 touchesBegan: 方法

这张图用多个气泡解释了我当前的设置:

在此处输入图像描述

代码:

@implementation Bubble
...
-(id) initWithFrame: (CGRect) frame {
    UITapGestureRecognizer *singleFingerDTap = [[UITapGestureRecognizer alloc]
                                                initWithTarget:self action:@selector(handleSingleTap:)];
    singleFingerDTap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:singleFingerDTap];

}

-(void) handleSingleTap {
NSLog(@"Bubble tapped, show the view");
}

广场

@implementation Square
...
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"square touched, lets hide the view");
}

点击后,我在控制台上看到了两个 NSLog

4

4 回答 4

6

嗯,这就是问题所在。touchesBegan将得到所有的触摸,包括手势识别器的触摸。您也可以尝试gestureRecognizer.cancelsTouchesInView = TRUE为气泡设置或使用 touchesBegan。

既然你好像在这里做游戏,你是在用 cocos2D 之类的引擎吗?如果是这样的话,有更简单的方法来完成你想要的。

希望这可以帮助。

干杯!

编辑:

如果您只使用手势识别器,触摸将不会发送到层次结构中的下一个视图。我想这就是你想要的。如果你决定开始接触,我认为你应该这样做:

//在气泡视图类中

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event 
{
    if(theTouchLocation is inside your bubble)
    {
        do something with the touch
    }
    else
    {
        //send the touch to the next view in the hierarchy ( your large view )
       [super touchesBegan:touches withEvent:event];
       [[self nextResponder] touchesBegan:touches withEvent:event];
    }
}
于 2012-10-09T06:42:18.877 回答
3

我发现了问题所在。UIView 继承自 UIResponder,基本的触摸事件由触发触摸开始事件的视图检测。您在主视图中添加的子视图也响应 touches started 方法。这是非常基本的。您还添加了一个带有点击手势识别器的选择器方法。因此,对气泡的任何触摸都会触发这两种方法,从而触发两个日志。尝试使用另一个选择器将另一个手势识别器添加到视图中,例如

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tappedOnBubble)];
    [self.bubbleView addGestureRecognizer:tap];

UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tappedOnMainView)];
   [self.view addGestureRecognizer:tap2];


-(void)tappedOnMainView
{
    NSLog(@"touched on main View");
    [self.vwToShow setHidden:NO];
}
-(void)tappedOnView
{
    NSLog(@"tapped on bubbleview");
    [self.vwToShow setHidden:YES];
}
于 2012-10-09T07:24:39.960 回答
1

做这个:

@implementation Square{

 ...
 -(id) initWithFrame: (CGRect) frame {
    UITapGestureRecognizer *singleFingerDTap = [[UITapGestureRecognizer alloc]
                                                initWithTarget:self action:@selector(handleSingleTap:)];
    singleFingerDTap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:singleFingerDTap];

 }

 -(void) handleSingleTap {
   NSLog(@"Sqaure tapped, hide the view");
 }

}
于 2012-10-09T06:43:16.473 回答
0

为什么不在主视图上也使用轻击手势识别器呢?触摸开始就像编写自己的手势识别器,但要困难得多。使用多个水龙头识别器,只有一个会触发。

于 2012-10-09T06:43:34.043 回答