How Long was a Touch Event – Detecting When a Touch Event Starts and Ends

Here’s a quick tip that shows how to determine the length of time from a begin touch event to an end touch event. I used a similar snippet of code recently when I had to determine if a user tapped on an image or held their finger on the image for a pre-determined amount of time.

Start by creating a variable of type NSTimeInterval to hold the time the touch event began.

// Define this as an instance variable
NSTimeInterval touchStartTime;
 
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{
  // When the touch event was detected
  touchStartTime = [event timestamp];
}

Inside the touchesBegan event, with some simple math, one can determine how long from the start event to the end.

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
{
  // Calculate how long touch lasted
  NSTimeInterval touchTimeDuration = [event timestamp] - touchStartTime;
 
  NSLog(@"Touch duration: %3.2f seconds", touchTimeDuration);
}

Comments are closed.