我有一个垂直滚动的UIScrollView
。我还想在其上处理水平平移,同时允许默认的垂直滚动行为。我在滚动视图上放置了一个透明的UIView
,并为其添加了一个平移手势识别器。这样我可以很好地获得平底锅,但滚动视图不会收到任何手势。
我已经实现了以下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);
}
答案 0 :(得分:44)
好的,我明白了。我需要做两件事来完成这项工作:
1)将我自己的声相识别器附加到滚动视图本身,而不是附加到其上的另一个视图。
2)这个UIGestureRecognizerDelegate
方法可以防止在同时调用默认的scrollview和我自己的scrollview时发生的愚蠢行为。
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
答案 1 :(得分:13)
我有同样的问题要解决,我这样做了:
1)将我自己的平移识别器附加到滚动视图。
2)返回YES: - gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:
这将允许两种手势都有效。那么这意味着在垂直滚动上,你的panGesture委托和scrollView委托都将被触发。如果它是水平滚动,它只会调用你的panGesture代表。
3)在我的panGesture委托中,检测它是否为水平滚动,如果不是,则忽略。
答案 2 :(得分:3)
快速回答:
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
}
}