Search code examples
cocoa-touchios6

Press and hold button iOS


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?


Solution

  • 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);    
    }