可能重复:
如何暂停/播放 NSTimer?
我有三个按钮start
stop
和pause
..我的start
和stop
按钮在下面的代码中工作正常..但是当按下Pause
它时暂停计时器..但是当我再次按下开始时.它从新添加的时间继续......而不是从暂停时间……
假设我在开始的 5 秒处暂停并等待 5 秒然后按开始...它应该显示 5 ...但显示 10 ..
因为我没有提到 (timer:)
......它将如何添加timer!=nill
......start
我有问题:
Pause
不工作。
-(void)start:(NSTimer *)timer
{
if(_timer==nil)
{
startDate =[NSDate date];
_timer=[NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
}
if(_timer!=nil)
{
float pauseTime = -1*[pauseStart timeIntervalSinceNow];
[_timer setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];
}
}
-(void)timer:(NSTimer *)timer
{
NSInteger secondsSinceStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate];
NSInteger seconds = secondsSinceStart % 60;
NSInteger minutes = (secondsSinceStart / 60) % 60;
NSInteger hours = secondsSinceStart / (60 * 60);
NSString *result = nil;
if (hours > 0)
{
result = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
else
{
result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
label.text=result;
NSLog(@"time interval -> %@",result);
}
-(void)stop
{
if(_timer!=nil)
{
startDate=nil;
[_timer invalidate];
_timer = nil;
}
}
-(void)pause:(NSTimer *)timer
{
pauseStart = [NSDate dateWithTimeIntervalSinceNow:0];
previousFireDate = [_timer fireDate];
[_timer setFireDate:[NSDate distantFuture]];
}