Multi Touch Tutorial – Part 4

In this tutorial I will show you how to implement the swipe feature (pan an image left or right).

Welcome to the fourth part of the tutorial where we will see how to pan an image (move left or right). This tutorial borrows its source code from its predecessors.

What we want to do is move the image left or right when the user swipes his fingers in either direction. We do this in touchesMoved method. This is how the source code will look like

– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

if([timer isValid])
[timer invalidate];

NSSet *allTouches = [event allTouches];

switch ([allTouches count])
case 1: {
//The image is being panned (moved left or right)
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
CGPoint centerPoint = [touch locationInView:[self view]];

[imgView setCenter:centerPoint];

} break;
case 2: {
//The image is being zoomed in or out.

UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];
UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];

//Calculate the distance between the two fingers.
CGFloat finalDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:[self view]]
toPoint:[touch2 locationInView:[self view]]];

//Check if zoom in or zoom out.
if(initialDistance > finalDistance) {
NSLog(@”Zoom Out”);
else {
NSLog(@”Zoom In”);

} break;


Since only one touch is required to move the image left or right, the following code is executed when the total number of touches is one. We get the first touch and then get the position of the touch. We move the image by setting the position of the touch as the center of the UIImageView.

I hope this tutorial helped you learning better how to use the touch features of the iPhone SDK. The same basic primniple can be used in any kind of application.

The source code can be downloaded from here and please leave me your comments.

Happy Programing
iPhone SDK Articles

Leave a Reply

Your email address will not be published.