allemattio
allemattio

Reputation: 1848

Swift 3 UITapGestureRecognizer not receiving tap

I want to add a gesture recognizer to one of my views to detect taps, here is my code:

class DateTimeContainer: UIView, UIGestureRecognizerDelegate {
    override func awakeFromNib() {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(self.onTap))
        gesture.delegate = self
        self.addGestureRecognizer(gesture)
    }

    func onTap(_ gestureRecognizer: UITapGestureRecognizer) {
        openDatePicker()
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view?.tag != self.datePickerTag && !self.isDatePickerOpen() {
            return true
        }
        return false
    }
}

When I tap on my view the code enters into the gestureRecognizer shouldReceive method and enters the condition for which it returns true.

But the onTap method is never called, can someone tell me why?

EDIT

Adding self.isUserInteractionEnabled = true I managed to get it working. But it had a strange behaviour: it was like it received the tap only in the main view and not in subviews. So to make it simple I solved by adding a button inside my view and by using:

self.button?.addTarget(self, action: #selector(onTap), for: .touchUpInside)

Upvotes: 2

Views: 5190

Answers (4)

Ashok Kumar
Ashok Kumar

Reputation: 225

You can You Gesture

let recognizer = UITapGestureRecognizer(target: self,action:#selector(self.handleTap(recognizer:)))
userImage.isUserInteractionEnabled = true
    recognizer.delegate = self as? UIGestureRecognizerDelegate
userImage.addGestureRecognizer(recognizer)

And method call selector

func handleTap(recognizer:UITapGestureRecognizer) {

           // do your coding here on method 



        }

Upvotes: 1

hooliooo
hooliooo

Reputation: 548

You may have forgotten to do this:

self.isUserInteractionEnabled = true

Also, typically the UIViewController subclass is usually the target and contains the method used for the tap gesture.

You don't need to set a delegate for a tap gesture (usually)

Upvotes: 5

jo3birdtalk
jo3birdtalk

Reputation: 616

I noticed that you are adding your gesture on a UIView. As such, at that ViewController where you have added this ContainerView, inside the viewDidLoad method, add this line of code.

override func viewDidLoad() {
    super.viewDidLoad()
    self.YourContainerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(YourCurrentViewController.openDatePicker())))
    self.YourContainerView.isUserInteractionEnabled = true
}

Note. Do not forget to add isUserInteractionEnabled to true.

Upvotes: 0

Pritam
Pritam

Reputation: 165

Try Writing the codes

let gesture = UITapGestureRecognizer(target: self, action: #selector(self.onTap))
        gesture.delegate = self
        self.addGestureRecognizer(gesture)

inside init block not in awakeFromNib()

Upvotes: 0

Related Questions