暂停和恢复时间Xcode

时间:2014-07-20 22:26:40

标签: xcode nstimer

我知道无法使用NSTimer暂停计时器。我知道我必须存储日期并再次调用它。我已经尝试了所有解决方案,但我找不到任何成功的解决方案。所以我的问题是,有没有人知道如何暂停和恢复?

1 个答案:

答案 0 :(得分:0)

这对我有用。 创建了2个UIButtons('startButton'和'resetButton'),UILabel显示时间('timeLabel'),NSTimeInterval('pauseTimeInterval'),NSTimer(stopWatchTimer')并使用以下代码:

NSDate *pauseStart, *previousFireDate, *startDate;
NSTimeInterval pauseTimeInterval;
NSTimer *stopWatchTimer;


-(void)pauseTimer{
    pauseStart = [NSDate dateWithTimeIntervalSinceNow:0];
    previousFireDate = [self fireDate];
    [self setFireDate:[NSDate distantFuture]];
}


-(void)resumeTimer{
    float pauseTime = -1*[pauseStart timeIntervalSinceNow];
    [self setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];
}

-(IBAction)startTime:(id)sender {

    //start timer
    if ([startButton.titleLabel.text isEqualToString:@"Start"] && (![self.stopWatchTimer isValid]) && ([timeLabel.text isEqualToString:@"00:00:00"]))
{
        [startButton setTitle:@"Stop" forState:UIControlStateNormal];
        startDate = [NSDate date];
        startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
        self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                             target:self
                                           selector:@selector(updateTimer)
                                           userInfo:nil
                                            repeats:YES];


        resetButton.hidden = YES;

    }

    //pause timer
    else if (([self.stopWatchTimer isValid]) && ([startButton.titleLabel.text isEqualToString:@"Stop"]))
    {
        [startButton setTitle:@"Resume" forState:UIControlStateNormal];
        [self.stopWatchTimer pauseTimer];
        resetButton.hidden = NO;

    }

    //resume timer
    else {
        [startButton setTitle:@"Stop" forState:UIControlStateNormal];
        startDate = [NSDate date];
        startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
        [self.stopWatchTimer resumeTimer];
        resetButton.hidden = YES;

        }
    }

-(IBAction)resetTime:(id)sender {

    [self.stopWatchTimer invalidate];
    self.stopWatchTimer = nil;
    self.timeLabel.text = @"00:00:00";
    [startButton setTitle:@"Start" forState:UIControlStateNormal];
    pauseTimeInterval = 0.0;
    resetButton.hidden = YES;
}


-(void)updateTimer
{
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSString *timeString=[dateFormatter stringFromDate:timerDate];
    self.timeLabel.text = timeString;
    pauseTimeInterval = timeInterval;

}