Triggering UITapGestureRecognizers from overlapping Views

喜你入骨 提交于 2019-12-13 03:22:49

问题


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,

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:


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.



来源:https://stackoverflow.com/questions/53987529/triggering-uitapgesturerecognizers-from-overlapping-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!