Adding a UITapGestureRecognizer to a UIView is very straighforward. All you do is setup the gesture and then assign it to the view. Could not be much easier could it.
1 2 |
let tapRecogniser = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewPressed(_:))) myView.addGestureRecognizer(tapRecogniser) |
There are a couple of points just to hightlight.
Firstly if you are using a UIImageView then you will need to add in the following extra line before you add the gesture.
1 |
myImageView.userInteractionEnabled = true |
Secondly I just want to mention the Selector part. This has changed in Swift from being
1 |
Selector("viewPressed:") |
to what you see in the example where you reference the selection method with the class of the UIViewController
1 |
_ = UITapGestureRecognizer(target: self, action: #selector(MyViewController.viewPressed(_:))) |
Recently I have started putting these selector references into Selector extensions. Here I set an extension on the Selector class itself and then use a static variable to set the selector.
1 2 3 |
extension Selector { static let viewPressed = #selector(MyViewController.viewPressed(_:)) } |
Back in my UITapGestureRecognizer, I can now just reference that static variable and even use dot notation as Xcode will know its a Selector instance.
1 |
_ = UITapGestureRecognizer(target: self, action: .viewpressed) |
How you implement the Selector call will come down to your preference and it may be that a best practice will evolve with these items, but setting gestures on your views and making your application more interactive is certainly very easy.