Triggering UITapGestureRecognizers from overlappin

2019-08-18 03:46发布

I have one main view and 4 subviews of the mainview they all have their UITapGestureRecognizer, when I tap on one subview how can it be triggered both views. Example below,

view hierarchy

if I tap to subview 1 desired log would be:

subview1 is clicked
MainView is clicked

My Code

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")
}

it prints only subview clicked! Is it possible to trigger both gestureRecognizers since main is encapsulating other.

1条回答
Melony?
2楼-- · 2019-08-18 04:04

First you should conform to UIGestureRecognizerDelegate in your VC, and then implement the delegate func of shouldRecognizeSimultaneouslyWith. Inside the function, you should detect if the gestureRecognizer, and the otherGestureRecognizer are the wants you want, and if so, you should allow them to work simultaneously,

  • Conform to delegate, and Declare gesture recognizers outside of viewDidLoad (because you need to access them in the delegate method later.)

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

  • Initialize your recognizers, and set your VC as their delegate:

    mainGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(mainGestureActivated))
    subGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(subViewGestureActivated))
    mainGestureRecognizer.delegate = self
    subGestureRecognizer.delegate = self
    
  • Implement the delegate function mentioned above to allow simultaneous recognition for subView and mainView:

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

And if you want it to work for 4 different subviews, then you should check with else if statements inside the delegate method.

查看更多
登录 后发表回答