【问题标题】:Adding a UITapGesture to UIScrollView将 UITapGesture 添加到 UIScrollView
【发布时间】:2017-06-13 18:45:16
【问题描述】:

我有一个 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)

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

【问题讨论】:

    标签: ios swift uiscrollview uigesturerecognizer uitapgesturerecognizer


    【解决方案1】:

    看看UIGestureRecogniserDelegate 函数。

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

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

    注意:确保您的类符合 UIGestureRecogniserDelegate 协议,并且您将手势委托设置为自我。

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

    更新:

    如果您尝试在动画期间识别点击,您可能需要在 UIView.animateWithDuration 的选项中使用 UIViewAnimationOptions.AllowUserInteraction 选项。使用另一个answer 作为来源

    【讨论】:

    • 我已经有 shouldRecognizeSimultaneouslyWith 方法,但始终返回 true。所以根据这个,点击应该在滚动时被识别?
    • 理论上是的,它应该可以工作。也许 scrollView 的委托设置不同。让我尝试复制问题并回复您
    • 我认为你正在关注滚动视图中的平移手势。抱歉,我更正了上面的 OP。问题是,当滚动动画发生时,而不是当用户拖动时......
    • 好的,我明白了。你想从水龙头里得到什么?
    • 每当我在动画时点击..动画停止并调用点击。请参阅测试项目中单个视图控制器的 Gist。 (您可能需要添加图像并更改名称)
    猜你喜欢
    • 2012-02-14
    • 2015-06-29
    • 2017-12-19
    • 2023-03-28
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多