从重叠视图触发 UITapGestureRecognizers

Triggering UITapGestureRecognizers from overlapping Views

我有一个主视图和主视图的 4 个子视图,它们都有自己的 UITapGestureRecognizer,当我点击一个子视图时,如何触发两个视图。下面的示例,

如果我点击以查看 1 个所需日志,则为:

subview1 is clicked
MainView is clicked

我的代码

override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let mainGesture = UITapGestureRecognizer(target: self, action: #selector(mainGestureActivated))

    self.view.addGestureRecognizer(mainGesture)

    let subGesture = UITapGestureRecognizer(target: self, action: #selector(subViewGestureActivated))

    self.subview1.addGestureRecognizer(subGesture)


}

@objc func mainGestureActivated(){
    print("MainView Clicked")
}

@objc func subViewGestureActivated(){
    print("Subview Clicked")
}

它只打印被点击的子视图!是否可以同时触发两个 gestureRecognizers,因为 main 正在封装其他。

首先你应该在你的VC中符合UIGestureRecognizerDelegate,然后实现shouldRecognizeSimultaneouslyWith的委托函数。在函数内部,你应该检测gestureRecognizerotherGestureRecognizer是否是你想要的,如果是,你应该让他们同时工作,

  • 符合委托,并在viewDidLoad之外声明手势识别器(因为稍后需要在委托方法中访问它们。)

    var mainGestureRecognizer = UITapGestureRecognizer() var subGestureRecognizer = UITapGestureRecognizer()

  • 初始化您的识别器,并将您的 VC 设置为它们的代表:

    mainGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(mainGestureActivated))
    subGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(subViewGestureActivated))
    mainGestureRecognizer.delegate = self
    subGestureRecognizer.delegate = self
    
  • 实现上面提到的delegate函数,实现subView和mainView同时识别:

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer == subGestureRecognizer && otherGestureRecognizer == mainGestureRecognizer {
            return true
        }
    
        return false
    }
    

如果你想让它为 4 个不同的子视图工作,那么你应该检查委托方法中的 else if 语句。