将 UITapGesture 添加到 UIScrollView

Adding a UITapGesture to UIScrollView

我有一个 UIScrollView。我对它做了一个点击手势:

self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:)))
self.tapGesture.delegate = self
self.tapGesture.numberOfTapsRequired = 1
self.tapGesture.numberOfTouchesRequired = 1
self.tapGesture.cancelsTouchesInView = false
self.tapGesture.delaysTouchesBegan = false
self.tapGesture.delaysTouchesEnded = false
self.scrollView.addGestureRecognizer(self.tapGesture)

这工作正常,除非滚动视图正在滚动(滚动动画正在发生,而不是用户拖动),点击手势被忽略。

我如何为滚动视图设置动画:

UIView.animate(withDuration: 0.3, delay: 0.0,
                           options:[.beginFromCurrentState, .curveEaseInOut], animations:
    {
        self.scrollView.contentOffset = CGPoint(x:self.scrollView.contentOffset.x, y:yOffset)
    },  completion: nil)

这个滚动视图大部分时间都在滚动,我试图让它在滚动视图动画滚动时识别点击手势 ....

查看 UIGestureRecogniserDelegate 函数。

您应该可以使用以下函数指定同时识别平移和点击手势:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, 
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return (gestureRecogniser is UIPanGestureRecogniser || gestureRecogniser is UITapGestureRecogniser) && (otherGestureRecognizer is UIPanGestureRecogniser || otherGestureRecognizer is UITapGestureRecogniser) 
}

注意:确保您的 class 符合 UIGestureRecogniserDelegate 协议并且您将手势委托设置为 self。

这应该可以,但我现在无法对其进行全面测试。

更新:

如果您试图在动画中识别点击,您可能需要使用 UIView.animateWithDuration 选项中的 UIViewAnimationOptions.AllowUserInteraction 选项。使用此其他 answer 作为来源