I need to implement a feature that will invoke some code when I double tap on the self.view (view of UIViewCotroller
). But the problem that I have other UI obje
If you don't want your 'double-tap recogniser' to conflict with your buttons and/or other controls, you can set self
as UIGestureRecognizerDelegate
and implement:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
{
return !(touch.view is UIControl)
}
Variant using CGPoint you touch (SWIFT 4.0)
class MyViewController: UIViewController, UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Get the location in CGPoint
let location = touch.location(in: nil)
// Check if location is inside the view to avoid
if viewToAvoid.frame.contains(location) {
return false
}
return true
}
}
Plus the above solutions, do not forget to check User Interaction Enabled
of your sub-view.
I had to prevent the gesture on the child view. The only thing that worked is to allow and keep the first view and prevent gesture in all the next views:
var gestureView: UIView? = nil
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if (gestureView == nil || gestureView == touch.view){
gestureView = touch.view
return true
}
return false
}
And for the Swift variant:
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if touch.view.isDescendantOfView(yourSubView){
return false
}
return true
}
Good to know, isDescendantOfView
returns a Boolean
value indicating whether the receiver is a subview of a given view or identical to that view.
Clear Swift way
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return touch.view == self.view
}