iOS:截取从顶视图到底视图的轻击手势事件

时间:2014-12-27 02:06:27

标签: ios objective-c cocoa-touch

在我的视图控制器中,我向self.view添加了一个UITapGestureRecognizer。我在self.view上添加了一个小视图。当我点击小视图时,我不想在self.view中触发UITapGestureRecognizer事件。这是我的代码,它不起作用。

    - (void)viewDidLoad {
    [super viewDidLoad];

    UITapGestureRecognizer *_tapOnVideoRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleControlsVisible)];

    [self.view addGestureRecognizer:_tapOnVideoRecognizer];

    UIView *smallView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    smallView.backgroundColor=[UIColor redColor];
    smallView.exclusiveTouch=YES;
    smallView.userInteractionEnabled=YES;

    [self.view addSubview:smallView];
    }

    - (void)toggleControlsVisible
    {
        NSLog(@"tapped");
    }

当我点按小视图时,它仍会在self.view中触发点击事件。 Xcode记录“轻拍”。如何拦截从smallView到self.view的手势事件?

1 个答案:

答案 0 :(得分:7)

像这样实施UIGestureRecognizer委托方法shouldReceiveTouch。如果触摸位置在topView内,请不要接触。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint location = [touch locationInView:self.view];

    if (CGRectContainsPoint(self.topView.frame, location)) {
        return NO;
    }
   return YES;
}