Justin Justin - 1 month ago 9
Swift Question

Using TapGestureRecognizer Proper Syntax

Can anyone help me out with this error? Not sure what it's asking for...

TapGestureRecognizer Syntax

override func viewDidLoad() {
super.viewDidLoad()

let tapStart = UITapGestureRecognizer(target: self, action:#selector(tapped(gesture:)))
self.view.addGestureRecognizer(tapStart)

func tapped(gesture: UITapGestureRecognizer){
print("It actually worked")
}
}


my end goal seems like it should be fairly simple:

I want to segue to another view when the user taps anywhere on the screen. I'm creating a TapGestureRecognizer and for now am simply printing to the logs as the method so I can easily see if it works.

Thanks!

Answer

Try using #selector(tapped(gesture:)) if you're on Swift 3. If you're on Swift 2 the selector will probably be tapped(_:) or something instead.

The compiler will ensure the existence of the symbol you're referencing when you use #selector. If you use a string and let the compiler create a Selector from the string literal, all you get is a warning like this. Same disadvantage goes for using the Selector("funcname") constructor.