33

我有一個垂直滾動UIScrollView。我也想處理水平鍋,同時允許默認的垂直滾動行爲。我在滾動視圖上放置了一個透明的UIView,併爲其添加了一個平移手勢識別器。通過這種方式,我可以很好地使用平底鍋,但滾動視圖不會收到任何手勢。通過UIScrollView截取平移手勢中斷滾動

我已經實現了以下UIPanGestureRecognizerDelegate方法,希望能夠限制我的手勢識別器只水平平底鍋,但是這並沒有幫助:

- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer 
{ 
    // Only accept horizontal pans here. 
    // Leave the vertical pans for scrolling the content. 
    CGPoint translation = [gestureRecognizer translationInView:self.view]; 
    BOOL isHorizontalPan = (fabsf(translation.x) > fabsf(translation.y)); 
    return isHorizontalPan; 
} 

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer 
{ 
    return (otherGestureRecognizer == _scrollView.panGestureRecognizer); 
} 
+1

你試過'[panGesture setCancelsTouchesInView:NO];'?在'shouldRecognizeSimultaneouslyWithGestureRecognizer'中簡單地返回YES也許可以幫助你找出問題出在哪裏。 –

+0

剛剛嘗試過,沒有區別。 – Macondo2Seattle

回答

33

OK,我想它了。我需要做2件事才能做到這一點:

1)將我自己的pan識別器附加到滾動視圖本身,而不是附加到它的頂部的另一個視圖。

2)這個UIGestureRecognizerDelegate方法可以防止當默認的scrollview和我自己的同時被調用時發生的愚蠢行爲。

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

shouldRecognizeSimultaneouslyWithGestureRecognizer的默認行爲是返回NO,因此add不需要 –

+4

將返回值更改爲YES,並且它工作得很好。 –

11

我不得不解決同樣的問題,我這樣做:

1)將我自己的鍋識別滾動視圖。

2)返回YES上: - gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:

這將使雙方的姿態工作。所以這意味着在垂直滾動時,panGesture委託和scrollView委託都會被觸發。如果是橫向滾動,則只會調用您的panGesture委託。

3)在我的panGesture委託中,檢測它是否是水平滾動,如果不是,忽略。

+1

這與我在我自己的回答中推薦的完全一樣。 – Macondo2Seattle

+11

@BlackRider不是。這將返回YES –

+0

謝謝'gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer'做了訣竅。 – atulkhatri

0

斯威夫特答案:

let scrollViewPanGesture = UIPanGestureRecognizer(target: self, action: #selector(onPan(_:))) 
scrollViewPanGesture.delegate = self 
scrollView.addGestureRecognizer(scrollViewPanGesture) 

extension ViewController: UIGestureRecognizerDelegate { 
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { 
     return true 
    } 
} 
相關問題