UIView关联多个Gesture

彭华皓
2023-12-01

如果一个UIView关联多个UIGestureRecognizer, 会发生一个奇怪的问题,如下面代码

    UIPanGestureRecognizer *pang = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panned:)];
    [self.view addGestureRecognizer:pang];
    
    UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
    [self.view addGestureRecognizer:swip];
- (void)swip:(UISwipeGestureRecognizer *)gesture {
    NSLog(@"swip");
}

- (void)panned:(UIPanGestureRecognizer *)gesture {
    NSLog(@"pan");
}

结果是看不到swip的手势触发。


原因是系统event传递是,当有一个相响了,event就不会传递下去了。

要想两个gesturerecognizer都起作用,只需要加几行代码就可以了

swip.delegate = self;

然后实现,返回YES,表示还要响应otherGestureRecognizer.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

这下就可以看到swip在consol中打印出来。






 类似资料: