如何为 UIViewController.view 中也具有 UITapGestureRecognizer 的 UIView 挑选和操作 UITapGestureRecognizer?

Posted

技术标签:

【中文标题】如何为 UIViewController.view 中也具有 UITapGestureRecognizer 的 UIView 挑选和操作 UITapGestureRecognizer?【英文标题】:How to single out and action a UITapGestureRecognizer for a UIView that is in the UIViewController.view that also has a 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 是的,请 【参考方案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

【讨论】:

以上是关于如何为 UIViewController.view 中也具有 UITapGestureRecognizer 的 UIView 挑选和操作 UITapGestureRecognizer?的主要内容,如果未能解决你的问题,请参考以下文章

UIViewController.View.Window 在 ViewDidLoad 方法中为空

移除 uiviewcontroller view ipad 的圆角

在swift中,如何在顶部保持一个UIViewController().view?比如UIAlertController

UITextView 设置为空,返回 UIViewController 时不会更新

django:DetailView 如何为两个模型工作或基于类的视图如何为两个模型工作?

如何为@Valid 指定验证组?