Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track a long hold for a finger in iPhone?

How could I track an event like touch on iPhone screen for 2 seconds. Like in Safari to save image for image added to a UIWebView?

like image 331
Tharindu Madushanka Avatar asked Dec 30 '22 03:12

Tharindu Madushanka


1 Answers

Create an NSTimer with +scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: in your view's -touchesBegan:withEvent: method, and cancel it (using -invalidate) in -touchesEnded:withEvent:. If the method its selector points at gets called, then the user held their finger on the view for whatever duration you set the timer's interval to. Example:

Interface (.h):

@interface MyView : UIView
    ...
    NSTimer *holdTimer;
@end

Implementation (.m):

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)evt
{
    [holdTimer invalidate];
    holdTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(touchWasHeld) userInfo:nil repeats:NO];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)evt
{
    [holdTimer invalidate];
    holdTimer = nil;
}

- (void)touchWasHeld
{
    holdTimer = nil;
    // do your "held" behavior here
}
like image 170
Noah Witherspoon Avatar answered Jan 05 '23 01:01

Noah Witherspoon