Xamarin: Simple GestureRecognizer

So i wanted to implement a basic pan gesture to pan around a view.

I need to use gesture recognizes to handle this and the process is remarkably easy.

Each view has the .AddGestureRecognizer() method that allows you to attach a number of gesture recognizes to a view.  If i want a view to handle a pan gesture I add a UIPanGestureRecogniser to the view in the ViewDidLoad().

var panGesture = new UIPanGestureRecognizer (PanHandler);
panGesture.MaximumNumberOfTouches = 2;          
this.View.AddGestureRecognizer (panGesture);

Each view can handle multiple gesture recognizes.  Number of touches is the number of fingers to detect.

Here i detect rotation.

var rotationGesture = new UIRotationGestureRecognizer (RotateHandler);
this.View.AddGestureRecognizer (rotationGesture);

The following gestures can be detected.  From Apple Development Docs.

  • Tapping – UITapGestureRecognizer
  • Pinching – UIPinchGestureRecognizer
  • Panning – UIPanningGestureRecognizer
  • Swiping -UISwipeGestureRecognizer
  • Rotation -UIRoationGestureRecognizer
  • LongPress -UILongPressGestureRecognizer

When a gesture is detected the handler will be called the the gesture state will change.  So in PanHandler we detect the current state and process accordingly.

void PanHandler (UIPanGestureRecognizer gestureRecognizer)

    var image = gestureRecognizer.View;
    if (gestureRecognizer.State == UIGestureRecognizerState.Began 
        || gestureRecognizer.State == UIGestureRecognizerState.Changed) 

        lblGesture.Text = "Pan: " + gestureRecognizer.LocationOfTouch (0,image).ToString ();          

The location of touch gets the position of the fingers during the pan.  You can use this information to move items or views around etc.

The gesture recognizer for other gesture types also contain useful information e.g. the amount of rotation during a rotation or the direction of a swipe.

This is just the beginning of what Gesture Recognizers can do.