UISwipeGestureRecognizer和UIPanGestureRecognizer 加到同一View怎样区分.

在项目开发的时候我们可能会遇到这样的需求.将UISwipeGestureRecognizer和UIPanGestureRecognizer 加到同一View.然后还要区分出什么时候是Pan什么时候是Swipe.在再开发的时候突然遇到这样一个需求,查了一些资料这个问题算是解决了.希望能帮助有同样需求的人.话不多说直接上代码.

1.首先实例两个手势:

UISwipeGestureRecognizer *swipeGestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeEvent:)];

swipeGestureRight.direction = UISwipeGestureRecognizerDirectionRight;

[self.view addGestureRecognizer:swipeGestureRight];

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panEvent:)];

[self.view addGestureRecognizer:panGesture];

这个时候你运行发现只会走Pan手势完全不会走Swipe.

2.做这样一个设置就可以区分Pan和Swipe

[panGesture requireGestureRecognizerToFail:swipeGestureRight];

这个方法在文档中的描述是这样的:

- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer

This method creates a relationship with another gesture recognizer that delays the receiver’s transition out of UIGestureRecognizerStatePossible. The state that the receiver transitions to depends on what happens with otherGestureRecognizer:

If otherGestureRecognizer transitions to UIGestureRecognizerStateFailed, the receiver transitions to its normal next state.

if otherGestureRecognizer transitions to UIGestureRecognizerStateRecognized or UIGestureRecognizerStateBegan, the receiver transitions to UIGestureRecognizerStateFailed.


意思是后面的这个手势要是识别成功的话就不会执行前一个手势了.如果后一个手势的state是UIGestureRecognizerStateFailed 接收者转换到其正常的下一个状态。换句话说它会优先识别Swipe手势如果不是swipe再识别是否是Pan手势.如果识别是Swipe则就执行Swipe的方法.不走Pan方法了.

PS:要想识别为Pan手势滑动的时候一定要尽量慢一些,否则直接就识别为Swipe了.

3.如果这样还是不行的话你可以做一个这样的设置:

当前类遵循UIGestureRecognizerDelegate然后指定代理对象:

swipeGestureRight.delegate = self;

panGesture.delegate = self;


然后执行

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer

shouldRecognizeSimultaneouslyWithGestureRecognizer:

(UIGestureRecognizer *)otherGestureRecognizer {

return YES;}

这个代理方法.
这个delegate的作用是否允许手势识别器同时识别两个手势.YES允许,NO不允许. 这样应该就可以了! 有什么问题的话希望大家指出,必虚心接受.
PS:这个同样适用其他的手势冲突.比如Tap手势设置为单击和双击两个,放在同一个View上也会有冲突,这个方法宜可解决.

你可能感兴趣的:(UISwipeGestureRecognizer和UIPanGestureRecognizer 加到同一View怎样区分.)