21

I tried to make a simple tap gesture and I can't figure it out. I want to add a target, simple selector to the gesture.

Here is my code :

var panGesture : UIGestureRecognizer = UITapGestureRecognizer.addTarget(<#UIGestureRecognizer#>)

How can I set selector?

timbo
  • 13,244
  • 8
  • 51
  • 71
Ron
  • 331
  • 1
  • 2
  • 11

2 Answers2

48

Should look something like this:

var tapGesture = UITapGestureRecognizer(target: self, action: "SomeMethod")
self.view.addGestureRecognizer(tapGesture)
yunas
  • 4,143
  • 1
  • 32
  • 38
Kris Gellci
  • 9,539
  • 6
  • 40
  • 47
  • 1
    Just gonna say that naming a `TapGesture` `panGesture` is in bad form (and I know you were copying the OP) – David Berry Jun 06 '14 at 16:07
  • Haha, changed it, I had written the entire thing as a pan gesture at first, realized the question was for a tap and I forgot to change the var name. – Kris Gellci Jun 06 '14 at 16:08
  • are you supposed to import something other than UIKit? I cant get this to work! – Chet Aug 01 '14 at 19:25
  • 5
    _let tapGesture_ better than _var tapGesture_ – abanet Oct 27 '15 at 11:41
  • If the tap gesture is added to a `UIImageView` make sure that you have set `userInteractionEnabled = true` – shehanrg Feb 24 '16 at 19:29
  • 1
    As of Swift 3, this no longer works. Please see below answer by @Alvin George `let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tap(gesture:)))` is how I got it to work. – Devbot10 Jan 16 '17 at 06:19
10

Swift 3:

Adding Tap Gesture Target:

sampleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.sampleTapGestureTapped(recognizer:)))
self.view.addGestureRecognizer(sampleTapGesture!)

Associated Function:

func sampleTapGestureTapped(recognizer: UITapGestureRecognizer) {
        print("Tapping working")
    }
Alvin George
  • 14,148
  • 92
  • 64