Detecting and responding to a swipe gesture

How to

Detect and respond to a swipe gesture.

BlackBerry device showing a directional arrow moving upward from the bottom of the screen. Shows the swipe gesture.

Solution

Set the input mode to GESTURE and add an event listener

// Enable dispatch of gesture
Multitouch.inputMode = MultitouchInputMode.GESTURE;

// Define gesture to listen for and name of function to dispatch when it occurs
stage.addEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe);

Create the function that is called to react to your event

public function onSwipe(event:TransformGestureEvent):void
{
	var strSwipe:String = "";

	if ( event.offsetX == -1 ) strSwipe = "Swipe direction: Left";
	if ( event.offsetX == 1 ) strSwipe = "Swipe direction: Right";
    if ( event.offsetY == -1 ) strSwipe = "Swipe direction: Up";
    if ( event.offsetY == 1 ) strSwipe = "Swipe direction: Down";

    trace(strSwipe);
}

Build requirements

You must include the following classes in your application.

import flash.events.TransformGestureEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;

Discussion

To react to a swipe gesture, you should set the MultiTouchInputMode to GESTURE to dispatch gesture events. After you set the input mode, add an event listener to handle a GESTURE_SWIPE event. To add functionality, you can evaluate the event.offsetX and event.offsetY values in the function called by that listener to detect swipe direction and respond accordingly.