Swift3 iOS - How to make UITapGestureRecognizer trigger function

I am trying to add a UITapGesture to a UIButton so it will trigger a function when tapped. I am using Swift 3 and is getting some error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SwiftRunner.ViewController tapBlurButton]: unrecognized selector sent to instance 0x149e07610'

This is roughly what I have:

// Swift 3
import UIKit
class ViewController {

   @IBOutlet weak var qsBlurButton: UIButton!       

   override func viewDidLoad() {
      super.viewDidLoad()

      let tapGesture = UITapGestureRecognizer(target: self, action: Selector(("tapBlurButton")))
      qsBlurButton.addGestureRecognizer(tapGesture)
   }

   func tapBlurButton(sender: UITapGestureRecognizer) {
      print("Please Help!")
   }
}

From your code you are using swift 3.0 so change your selector syntax like this

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(_:)))

and Your function like this

func tapBlurButton(_ sender: UITapGestureRecognizer) {
    print("Please Help!")
}

Edit:

Not idea that you are using button with tap gesture, instead of that use inbuilt method addTarget for button no need to create tap gesture for it like this

qsBlurButton.addTarget(self, action: #selector(self.tapBlurButton(_:)), forControlEvents: .TouchUpInside)

func tapBlurButton(_ sender: UIButton) {
    print("Please Help!")
}

Swift 3

In the case where the func for the selector looks like this (note: it doesn't have a _):

func tapBlurButton(sender: UITapGestureRecognizer) {
  print("Please Help!")
}

Then the selector looks like this:

#selector(self.tapBlurButton(sender:))

So the final code for the selector is this:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(sender:)))

If you do not specify that the first parameter has _, then you need to use the full name of the first parameter.


To add a gesture recognizer you have to create one indicating which function it will call:

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleTapFrom(recognizer:)))

Then add it to the element you need. (You are using a button, and as others have explained buttons have their native 'addTarget' methods)

For explanation purposes imagine you want to add it to an UIView:

self.someView.addGestureRecognizer(tapGestureRecognizer)

And don't forget that some elements are "not user interactive" by default so you might have to change that property too:

self.someView.isUserInteractionEnabled = true

In Swift 4 the function needs the @objc declaration:

@objc func handleTapFrom(recognizer : UITapGestureRecognizer)
{
    // Some code...
}