Handling Tap Gestures

Use brief taps on the screen to implement button-like interactions with your content.


Tap gestures detect one or more fingers touching the screen briefly. The fingers involved in these gestures must not move significantly from the initial touch points, and you can configure the number of times the fingers must touch the screen. For example, you might configure tap gesture recognizers to detect single taps, double taps, or triple taps.

You can attach a gesture recognizer in one of these ways:

  • Programmatically. Call the addGestureRecognizer(_:) method of your view.

  • In Interface Builder. Drag the appropriate object from the library and drop it onto your view.

A diagram showing a single-finger tap gesture

A UITapGestureRecognizer object provides event handling capabilities similar to those of a button—it detects a tap in its view and reports that tap to your action method. Tap gestures are discrete, so your action method is called only when the tap gesture is recognized successfully. You can configure a tap gesture recognizer to require any number of taps—for example, single taps or double taps—before your action method is called.

Listing 1 shows an action method that responds to a successful tap in a view by animating that view to a new location. Always check the gesture recognizer’s state property before taking any actions, even for a discrete gesture recognizer.

Listing 1

Handling a tap gesture

@IBAction func tapPiece(_ gestureRecognizer : UITapGestureRecognizer ) {
   guard gestureRecognizer.view != nil else { return }
   if gestureRecognizer.state == .ended {      // Move the view down and to the right when tapped.
      let animator = UIViewPropertyAnimator(duration: 0.2, curve: .easeInOut, animations: {
         gestureRecognizer.view!.center.x += 100
         gestureRecognizer.view!.center.y += 100

If the code for your tap gesture recognizer is not called, check to see if the following conditions are true, and make corrections as needed:

See Also


Handling Long-Press Gestures

Detect extended duration taps on the screen, and use them to reveal contextually relevant content.

Handling Pan Gestures

Trace the movement of fingers around the screen, and apply that movement to your content.

Handling Swipe Gestures

Detect a horizontal or vertical swipe motion on the screen, and use it to trigger navigation through your content.

Handling Pinch Gestures

Track the distance between two fingers and use that information to scale or zoom your content.

Handling Rotation Gestures

Measure the relative rotation of two fingers on the screen, and use that motion to rotate your content.