Gesture Recognizers
A fun yet easy thing to do is play with Gesture Recognizers in swift. Something about making one, and then seeing it work just feels cool. You don’t do much work, you just write the code for the gesture and the magic happens. Just Name the gesture you want to use, set its target and the function you want called when the gesture is recognized.
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapHappened(sender:)))
The UITapGestureRecognizer is actually a subclass of UIGestureRecognizer and I’ll Touch on that later. But What’s cool about the subclasses is they each come with variables that you can set so that it works for that gesture. So for this Gesture I set its variables as shown.
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
The last thing so that this gesture can be used is you must set it to a specific UIView. Now even tho UIButton is a subclass of UIView, I haven’t tested whether or not it would work on that. You can try that if you’re curious but Buttons are made to be pressed. So the gesture you might put on a button would be UIPanGestureRecognizer or a UISwipeGestureRecognizer. To move it. or maybe a secret function. IDK go nuts that’s whats fun about programming. But I got off topic. here’s a view and a Gesture Hooked up to it.
let someView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))someView.addGestureRecognizer(doubleTap)
Of Course for this to work, you’d have to add the view to your project, or maybe the view is already in the storyboard then you’d just do the second line. Then Run your app, and double tap away. Just remember you need to make that function to be called when the gesture is recognized. Also, this probably shouldn’t be at the bottom, but the function should be prefixed with @objc
@objc func doubleTapHappened(sender: UITapGestureRecgonizer){
print("Double Tap Must Have Happened")
}