【问题标题】:How to single out and action a UITapGestureRecognizer for a UIView that is in the UIViewController.view that also has a UITapGestureRecognizer?如何为 UIViewController.view 中也具有 UITapGestureRecognizer 的 UIView 挑选和操作 UITapGestureRecognizer?
【发布时间】:2020-06-10 10:12:58
【问题描述】:

我有一个 UIView 对象,我添加了一个 UITapGestureRecognizer。主视图还有一个我用来隐藏键盘的 UITapGestureRecognizer。我如何优先考虑子 UIView 上的 tapGesture 来做我需要做的事情?我希望在点击子视图时触发与此点击相关的操作,而不是主视图的手势。

我尝试向子视图添加双击,以区分这两种手势,但这只会触发主视图的点击动作。

var childView: UIView!

 /**Tap screen event listener - to hide the keyboard*/
 let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(hideKeyBaord))
 self.view.addGestureRecognizer(tapGesture)


 let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(doSomethingElse))
 doubleTap.numberOfTouchesRequired = 2
 childView.view.addGestureRecognizer(doubleTap)

【问题讨论】:

  • “优先”是什么意思?您的意思是如果子视图的手势识别器激活,您不希望主视图的手势识别器激活?
  • @Sweeper 是的,请

标签: swift uigesturerecognizer


【解决方案1】:

一种方法是为tapGesture 实现shouldReceiveTouch 委托方法:

extension YourViewController : UIGestureRecognizerDelegate {
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if gestureRecogniser == tapGesture {
            // tapGesture should not receive the touch when the touch is inside the child view
            let location = touch.location(in: childView)
            return !childView.bounds.contains(location)
        } else {
            return true
        }
    }
}

记得将tapGesture 的委托设置为self

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多