Tuesday, July 27, 2010

Detecting Long press( Tap and hold) on iPhone application

I was creating one game for iPhone and I required to detect Tap and Hold (Long press ) gesture in application. After trying a bit and reading some documentation, I found following solution. Solution is to perform Selector with some delay, and cancel Selector if touch has ended before enough time is passed.

Following is code from my application.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch began");
[self performSelector:@selector(longTap) withObject:nil afterDelay:1.0];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch ended");
[NSObject cancelPreviousPerformRequestsWithTarget:self 
selector:@selector(longTap) object:nil];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touches moved");
[NSObject cancelPreviousPerformRequestsWithTarget:self 
selector:@selector(longTap) object:nil];
}

-(void) longTap 
{
NSLog(@"handle long tap..");
}

Hope this helps...

5 comments:

  1. Yes! Thanks! I was looking for something just like this and it works perfectly!!

    ReplyDelete
  2. Welcome, I am glad that it helped...

    ReplyDelete
  3. Why not use the UILongPressGestureRecognizer?
    It's a lot more elegant and straight forward...

    ReplyDelete
  4. UILongPressGestureRecognizer is introduced in new version of iPhone SDK. This API will not work on older version of iPhone SDK

    ReplyDelete
  5. //Add gesture to a method where the view is being created. In this example long tap is added to tile (a subclass of UIView):

    // Add long tap for the main tiles
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
    [tile addGestureRecognizer:longPressGesture];
    [longPressGesture release];

    -(void) longTap:(UILongPressGestureRecognizer *)gestureRecognizer{
    NSLog(@"gestureRecognizer= %@",gestureRecognizer);
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
    NSLog(@"longTap began");

    }

    }

    ReplyDelete