识别不在某个子视图中的手势

时间:2011-06-16 23:23:17

标签: iphone ios cocoa-touch uigesturerecognizer

我想使用UIGestureRecognizers来区分两种手势:那些在迷你UIView中发生的手势和在视图中其他任何地方发生的手势。

我认为我可以使用requireGestureRecognizerToFail使用两个GestureRecognizer来完成此任务。但是,父视图的GestureRecognizer永远不会触发。这是为什么?

这是一个示范性测试案例:

-(void)viewDidLoad {

    UIView *miniView = [[[UIView alloc] initWithFrame:CGRectMake(100,100,20,20)] autorelease];
    miniView.backgroundColor = [UIColor redColor];
    [self.view addSubview:miniView];

    // triggered when you tap the miniView
    UITapGestureRecognizer *miniTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(miniTap:)] autorelease];
    [miniView addGestureRecognizer:miniTap];

    // expected: triggered when you tap anywhere outside the mini-view
    // actual: never triggered!
    UITapGestureRecognizer *nonMiniTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nonMiniTap:)] autorelease];
    [nonMiniTap requireGestureRecognizerToFail:miniTap];
    [self.view addGestureRecognizer:nonMiniTap];


    [super viewDidLoad];
}


-(void)miniTap:(id)sender { NSLog(@"miniTap"); }

-(void)nonMiniTap:(id)sender { NSLog(@"nonMiniTap"); }

为什么requireGestureRecognizerToFail:阻止nonMiniTap被触发?我可以让它以预期的方式运作吗?

1 个答案:

答案 0 :(得分:2)

如果您看到requireGestureRecognizerToFail:的文档,则会清楚地说明手势的状态不会从UIGestureRecognizerStatePossible更改,直到其他手势转换为UIGestureRecognizerStateFailedUIGestureRecognizerStateRecognized 。但由于miniTap手势未移出其默认UIGestureRecognizerStatePossible状态,因为触摸不在其视图范围内,因此无法识别nonMiniTap手势。因此,您对父视图的点击失败。

因此不需要依赖。您可以关闭该行,它应该按照您的意愿工作。