Search code examples
iosiphone-sdk-2

How to get functionality of Long Press gesture in iOS below 3.2


UILongPressGesture is available in ios ver 3.2 and later. But i am trying to develop application for maximum compatibility and hence targeting ios ver2.0

Can anyone please guide me on how to accomplish long press gesture in ios v2.0


Solution

  • For a single finger, it's pretty simple: Start a timer in the touchesBegan method and trigger an action when the timer fires. Cancel the timer if you get a touchesEnded before it fires. Here's an implementation that uses the performSelector:withObject:afterDelay: method.

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [self performSelector:@selector(fireLongPress)
                   withObject:nil
                   afterDelay:LONG_PRESS_THRESHOLD];
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
    }
    
    - (void)fireLongPress {
        // do what you want to do
    }
    

    You'll probably also want to kill the timer if the finger moves too far.

    With multitouch, it's a bit more complicated. You'll have to keep track of which touch is which, and decide what to do e.g. when one finger has pressed long enough but the other hasn't (or figure out what UILongPressGestureRecognizer does).