Reputation: 1625
How can I add timer to detect how much time UIButton was pressed on iPhone?
Thanks
Upvotes: 2
Views: 2149
Reputation: 49344
Try this:
// somewhere in interface
NSDate *_startDate;
- (IBAction)buttonDown:(id)sender {
_startDate = [[NSDate date] retain];
}
- (IBAction)buttonUp:(id)sender {
NSTimeInterval pressedForInSeconds = [[NSDate date] timeIntervalSince1970] - [startDate timeIntervalSince1970];
NSLog(@"button was pressed for: %d seconds", pressedForInSeconds);
[_startDate release];
}
Then wire buttonDown:
action to "Touch down inside" outlet, and buttonUp:
to "Touch up inside" or "Touch up outside" outlet in button connections tab in Interface Builder.
Upvotes: 1
Reputation: 22726
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//Check here for touch is in your button frame than add
[self performSelector:@selector(judgeLongPresstime) withObject:nil afterDelay:YourDelayTimeCheck];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[NSObject cancelPreviousPerformRequestWithTarget:self];
}
-(void)judgeLongPresstime
{
//Add timer here and get time of increaseing.
}
Upvotes: 1
Reputation: 22698
Declare buttonPressedStartTime as a CFTimeInterval in your .h file.
When the button is pressed, store the current time:
buttonPressedStartTime = CFAbsoluteTimeGetCurrent();
When the users thouches up the binger,
float deltaTimeInSeconds = CFAbsoluteTimeGetCurrent() - buttonPressedStartTime;
Upvotes: 5