Use a Tap Gesture

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

In iOS, tap gestures are registered with the UITapGestureRecognizer class. This recipe demonstrates how to use this class to recognize single and multiple tap gestures.

Recipe

Tap Gesture Tap Gesture

  1. First, let's enable user interaction on the UI element that's going to receive the taps. We can do that by setting the UserInteractionEnabled property to true:

    imageView.UserInteractionEnabled = true;

    We can do this inside the ViewDidLoad method of the ViewController, or whatever method you are using to manipulate the UI element.

  2. Next we'll create a new UITapGestureRecognizer, passing in the name of the Action that will handle the tap gesture:

    UITapGestureRecognizer tapGesture = new UITapGestureRecognizer (TapThat);
  3. Next we'll create the Action to handle the tap gesture. In our example, we're using a method called TapThat to rotate the View 90 degrees clockwise and show an alert view:

    tap.View.Transform *= CGAffineTransform.MakeRotation ((float)Math.PI / 2);
                    tapped = true;
                    alert = UIAlertController.Create ("Card Tapped", "This card has been tapped", UIAlertControllerStyle.Alert);
                    alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null));
                    PresentViewController (alert, true, null);
  4. Finally, we can add the gesture recognizer to our UI element:

    imageView.AddGestureRecognizer (tapGesture);

Additional Information

We can control the number of taps our gesture recognizer responds to by editing the NumberOfTapsRequired property of the tap gesture recognizer. For example, we could change the code above to respond to two taps with the following code:

tapGesture.NumberOfTapsRequired = 2;

The default number of taps required is 1.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.