I haven't been programming in iOS for long but I was just wondering if anyone could help. I have a IBAction function and every time it is pressed increases a counter so I can see how many times it's been pressed. But I want to add functionality so when it's pressed I can display the time between each press. So if they press the button a one pops up. Then they press it again and 2 button presses pops up but also the amount of time since they pressed it. I'm not sure how to implement this because I'm not sure how I would find the time of the event. There is UIEvent's timestamp, but I'm not entirely sure how to use it.
Asked
Active
Viewed 1,238 times
2 Answers
3
Unless you need extreme accuracy it's probably enough to get the current time when your IBAction method is called in which case you could do something like this:
- (IBAction) buttonAction: (id) inButton
{
NSDate *now = [NSDate date];
if (self.lastEventTime != nil) {
NSTimeInterval timeSinceLast = [now timeIntervalSinceDate: self.lastEventTime];
NSLog(@"time since last press: %f seconds", timeSinceLast);
}
self.lastEventTime = now;
}
Here's how that might look in Swift:
class SomeController: UIViewController {
var lastEventTime : NSDate?
@IBAction func buttonAction(inButton: AnyObject) {
let now = NSDate()
if let lastEventTime = self.lastEventTime {
let timeSinceLast = now.timeIntervalSinceDate(lastEventTime)
println("time since last press: \(timeSinceLast) seconds")
}
self.lastEventTime = now
}
}

Casey Fleser
- 5,707
- 1
- 32
- 43
-
Sorry, I'm struggling to understand what's going on in your code. Where would this fit in terms of inside/outside my current IBAction func. (I'm working in Swift also) – DonnellyOverflow Sep 26 '14 at 17:47
-
Also, What is lastEventTime? – DonnellyOverflow Sep 26 '14 at 17:59
-
Sorry about that, forgot to provide an example in Swift. I've updated my example. Hopefully it's more clear. – Casey Fleser Sep 26 '14 at 18:14
-2
You could have a NSDate property which you assign every time, the event is fired. You then always compare the difference between the property and the current time.
@property (nonatomic) NSDate *lastEventDate;
- (IBAction) clicked:(id)sender{
NSDate *now = [NSDate date];
NSTimeInterval differenceBetweenDatesInSeconds = [self.lastEventDate timeIntervalSinceDate:now];
//Do something with the interval (show it in the UI)
[self setLastEventDate:now];
}

TMob
- 1,278
- 1
- 13
- 33