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.
First you should conform to
UIGestureRecognizerDelegate
in your VC, and then implement the delegate func ofshouldRecognizeSimultaneouslyWith
. Inside the function, you should detect if thegestureRecognizer
, and theotherGestureRecognizer
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:
Implement the delegate function mentioned above to allow simultaneous recognition for subView and mainView:
And if you want it to work for 4 different subviews, then you should check with else if statements inside the delegate method.