在項目開發(fā)的時候我們可能會遇到這樣的需求.將UISwipeGestureRecognizer和UIPanGestureRecognizer 加到同一View.然后還要區(qū)分出什么時候是Pan什么時候是Swipe.在再開發(fā)的時候突然遇到這樣一個需求,查了一些資料這個問題算是解決了.希望能幫助有同樣需求的人.話不多說直接上代碼.
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];
這個時候你運行發(fā)現(xiàn)只會走Pan手勢完全不會走Swipe.
2.做這樣一個設(shè)置就可以區(qū)分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.
意思是后面的這個手勢要是識別成功的話就不會執(zhí)行前一個手勢了.如果后一個手勢的state是UIGestureRecognizerStateFailed 接收者轉(zhuǎn)換到其正常的下一個狀態(tài)。換句話說它會優(yōu)先識別Swipe手勢如果不是swipe再識別是否是Pan手勢.如果識別是Swipe則就執(zhí)行Swipe的方法.不走Pan方法了.
PS:要想識別為Pan手勢滑動的時候一定要盡量慢一些,否則直接就識別為Swipe了.
3.如果這樣還是不行的話你可以做一個這樣的設(shè)置:
當前類遵循UIGestureRecognizerDelegate然后指定代理對象:
swipeGestureRight.delegate = self;
panGesture.delegate = self;
然后執(zhí)行
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:
(UIGestureRecognizer *)otherGestureRecognizer {
return YES;}
這個代理方法.
這個delegate的作用是否允許手勢識別器同時識別兩個手勢.YES允許,NO不允許. 這樣應(yīng)該就可以了! 有什么問題的話希望大家指出,必虛心接受.
PS:這個同樣適用其他的手勢沖突.比如Tap手勢設(shè)置為單擊和雙擊兩個,放在同一個View上也會有沖突,這個方法宜可解決.