Detecting Swipe Gestures

The iPhone can detect a number of gestures. In this tutorial we show how to detect the left and right swipe gesture. We will create a label which moves to the side of the swipe. This tutorial is built with Xcode 4.5 and built for iOS6. Let 's start. Create a new Project. Select Single View Application.

Update: Nov 21, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Enter the following project options

In iOSCiewController.xib drag a Label onto the middle half of the canvas.. Enter Swipe inside the label. Ctrl+ Drag from the label to iOSViewController.h between the @interface and @end section. Create the following IBOutlet.

Now that out label is into place, let's define the left and right gestures. In iOSViewController.m, create the following properties

@property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeGestureRecognizer; 
@property (nonatomic, strong) UISwipeGestureRecognizer *rightSwipeGestureRecognizer;

In iOSViewController.m, create the swipeRecognizer objects in viewDidload. When a swipe is detected, the handleSwipes method will be called.

self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];

Set the direction of the swipe with the direction property

self.leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
self.rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;

Finally, add the gestures the view

 

[self.view addGestureRecognizer:self.leftSwipeGestureRecognizer];
[self.view addGestureRecognizer:self.rightSwipeGestureRecognizer];

Now, let's create the handleSwipes method in iosViewController.m

 

- (void)handleSwipes:(UISwipeGestureRecognizer *)sender 
{
if (sender.direction == UISwipeGestureRecognizerDirectionLeft)
{
CGPoint labelPosition = CGPointMake(self.swipeLabel.frame.origin.x - 100.0, self.swipeLabel.frame.origin.y);
self.swipeLabel.frame = CGRectMake( labelPosition.x , labelPosition.y , self.swipeLabel.frame.size.width, self.swipeLabel.frame.size.height);
}


if (sender.direction == UISwipeGestureRecognizerDirectionRight)
{
CGPoint labelPosition = CGPointMake(self.swipeLabel.frame.origin.x + 100.0, self.swipeLabel.frame.origin.y);
self.swipeLabel.frame = CGRectMake( labelPosition.x , labelPosition.y , self.swipeLabel.frame.size.width, self.swipeLabel.frame.size.height);
}
}

The x-coordinate from the label position will be added/subtracted with 100 point to move the label left or right onto the view. That's it. Build and Run the Project and perform a swipe.

You can download the source code of the iOSSwipeTutorial at the ioscreator repository on github.