UIScrollView timer
I have a UIScrollView
and want to set a timer, so if I scroll and do nothing for about 10 seconds a job method will be called, and if I scroll before this 10 seconds the timer will reset. My code doesn't work.
// Global vars
NSDate *startDate, *endDate;
// myTimer (NSTimer ) and timerIsValid(BOOL) are part of my viewController class
- (BOOL)timerExpired
{
NSDate *dateNow=[NSDate date];
if ([[dateNow laterDate:endDate] isEqual:endDate]) {
return YES;
}
else {
return NO;
}
}
// If i b开发者_运维百科egin scrolling i want to stop the timer
- (void)scrollViewWillBeginDragging:(UIScrollView *)myScrollView
{
// Check if the timer is alive and invalidate it
if ([self timerExpired] == NO) {
NSLog(@"TIMER STILL ALIVE...KILL IT");
[myTimer invalidate];
myTimer = nil;
timerIsValid = NO;
}
else {
NSLog(@"TIMER IS DEAD");
timerIsValid = YES;
}
}
// After 10 seconds if i didn't scroll, i want to some job
- (void)scrollViewDidEndDecelerating:(UIScrollView *)myScrollView
{
if (endDate) {
[endDate release];
}
startDate = [NSDate date];
endDate = [[startDate addTimeInterval:10.0] retain];
if (!myScrollView.dragging)
{
if (autoscrollTimer == nil) {
// Create a new timer
myTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(timerFireMethod:)
userInfo:nil
repeats:YES];
}
}
}
- (void)timerFireMethod:(NSTimer*)theTimer
{
if (timerIsValid) {
// do nothing
NSLog(@"DO NOTHING");
}
else {
NSLog(@"DO SOME JOB");
[self doSomeJob];
timerIsValid = YES;
}
}
NSTimer *_scrollTimer; // instance variable
- (void)scrollViewWillBeginDragging:(UIScrollView *)myScrollView
{
[_scrollTimer invalidate]
_scrollTimer = nil;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)myScrollView
{
assert(_scrollTimer == nil);
_scrollTimer = [NSTimer scheduledTimerWithTimeInterval:10
target:self
selector:@selector(timerFireMethod:)
userInfo:nil
repeats:NO];
}
- (void)timerFireMethod:(NSTimer *)theTimer
{
_scrollTimer = nil;
NSLog(@"DO SOME JOB");
}
精彩评论