Skip to content

Instantly share code, notes, and snippets.

@diversario
Last active September 28, 2017 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diversario/bf9ebf6a1c92ed95b3a9 to your computer and use it in GitHub Desktop.
Save diversario/bf9ebf6a1c92ed95b3a9 to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
let tapGestureRecognizer: UITapGestureRecognizer! // make a variable to hold the recognizer
@IBOutlet weak var girImage: UIImageView! // add an outlet for your image view
override func viewDidLoad() {
super.viewDidLoad()
// make an instance of tap recognizer
// add your view controller as the target and tell it to call method named "onImageTapped:"
// Make sure to have that colon at the end!
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onImageTapped:")
// add your recognizer to your image
girImage.addGestureRecognizer(tapGestureRecognizer)
// enable user interactions or it won't work!
girImage.userInteractionEnabled = true
}
func onImageTapped(sender: AnyObject) {
print("It works from code too!")
}
}
@CoBug92
Copy link

CoBug92 commented Sep 28, 2017

Swift 3 had been changed:
let avatarGesture = UIGestureRecognizer(target: self, action: #selector(onImageTapped(sender:)))

And the better way is using _ instead using variable in function in this case

 func onImageTapped(_ sender: AnyObject) {
        print("It works from code too!")
    }

Now
let avatarGesture = UIGestureRecognizer(target: self, action: #selector(onImageTapped(_:)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment