0

I'm a newbie to IOS development, and have a bit of java and Arduino programming experience. I am working on a simple morse code project. How can I keep track the amount of time a button is pressed in iOS? Would I just have to have a big loop which keeps scanning for the button being pressed?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Skyler 440
  • 103
  • 6
  • possible duplicate of [UIButton long press with finger stationary](http://stackoverflow.com/questions/9389923/uibutton-long-press-with-finger-stationary) – jprofitt Aug 17 '13 at 14:42

2 Answers2

3

I would do something like this:

Add a property to your class to store the date of the latest touch down. Preferably in a class extension in the .m-file.

@interface YourViewController ()
@property (nonatomic, strong) NSDate *buttonTouchDownDate;
@end

Connect your button, programmatically or with interface builder, to the Touch Down and Touch Up Inside control events. This is described in great detail here.

Then store the date when the button was touched down. When the finger is lifted, calculate the time interval between the stored date and now.

- (IBAction)buttonDidTouchDown:(id)sender
{
    self.buttonTouchDownDate = [NSDate date];
}
- (IBAction)buttonDidTouchUp:(id)sender
{
    // Will return a negative value, so we use the ABS-macro.
    NSTimeInterval timeInterval = ABS([self.buttonTouchDownDate timeIntervalSinceNow]); 
    NSLog(@"Time interval: %f", timeInterval);    
}
Community
  • 1
  • 1
Johannes Lund
  • 1,897
  • 2
  • 19
  • 32
0

You have to combine 2 functions results:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

there you get the start time.

And

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  if (self.touchInside) {
    NSLog(@"TouchUpInside");
  } else {
    NSLog(@"TouchUpOutside");
  }
}

if if a touchupinside than you get the "endtime" and calculate the duration.