Gesture Recognizers are an powerful way to build interactions into your app. Let's look at the basics with a couple of example use cases:
Two Finger Long Press
Here we'll build a gesture that fires when the user touches the screen with two fingers for 1 second.
func handleLongPressGesture(gr: UILongPressGestureRecognizer) {
sendHeartbeat()
}
let longPressGR = UILongPressGestureRecognizer(
target: self,
action: "handleLongPressGesture:"
)
// we allow user some 'wiggle' so the recognizer
// doesn't fail if they move slightly while touching
longPressGR.allowableMovement = 80
longPressGR.minimumPressDuration = 1 // in seconds
longPressGR.numberOfTouchesRequired = 2
digitalTouchView.addGestureRecognizer(longPressGR)
Make a View Draggable
Ever wanted to enable a view to be dragged around the screen? A pan gesture recognizer does the trick:
func handlePanGesture(gr: UIPanGestureRecognizer) {
guard gr.state != .Ended && gr.state != .Failed else { return }
gr.view!.center = gr.locationInView(gr.view!.superview!)
}
let panGR = UIPanGestureRecognizer(
target: self,
action: "handlePanGesture:"
)
panGR.minimumNumberOfTouches = 1
panGR.maximumNumberOfTouches = 1
moveableView.addGestureRecognizer(panGR)