在iPhone中暂停秒表计时器?

时间:2011-10-21 12:51:25

标签: iphone objective-c xcode

我是iPhone新手NSTimer。我做了一个秒表。现在我想暂停两次之间的时间 并且还希望恢复暂停。我的代码如下。

  • 我该如何暂停时间?
  • 我怎样才能从时间停止的地方恢复?

开始时间:

startDate = [[NSDate date]retain];
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                                      target:self
                                                    selector:@selector(updateTimer)
                                                    userInfo:nil
                                                     repeats:YES];

停止时间:

[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer];

更新时间:

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

6 个答案:

答案 0 :(得分:5)

您可以使用NSTimeInterval而不是计时器。我有一个功能代码来暂停和停止计时器。

@interface PerformBenchmarksViewController () {

    int currMinute;
    int currSecond;
    int currHour;
    int mins;
    NSDate *startDate;
    NSTimeInterval secondsAlreadyRun;
}

@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    running = false;
}

- (IBAction)StartTimer:(id)sender {

    if(running == false) {

        //start timer
        running = true;
        startDate = [[NSDate alloc] init];
        startTime = [NSDate timeIntervalSinceReferenceDate];
        [sender setTitle:@"Pause" forState:UIControlStateNormal];
        [self updateTime];
    }
    else {
        //pause timer
        secondsAlreadyRun += [[NSDate date] timeIntervalSinceDate:startDate];
        startDate = [[NSDate alloc] init];
        [sender setTitle:@"Start" forState:UIControlStateNormal];
        running = false;
    }
}

- (void)updateTime {

    if(running == false) return;

    //calculate elapsed time
    NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
    NSTimeInterval elapsed = secondsAlreadyRun + currentTime - startTime;

    // extract out the minutes, seconds, and hours of seconds from elapsed time:
    int hours = (int)(mins / 60.0);
    elapsed -= hours * 60;
    mins = (int)(elapsed / 60.0);
    elapsed -= mins * 60;
    int secs = (int) (elapsed);

    //update our lable using the format of 00:00:00
    timerLabel.text = [NSString stringWithFormat:@"%02u:%02u:%02u", hours, mins, secs];

    //call uptadeTime again after 1 second
    [self performSelector:@selector(updateTime) withObject:self afterDelay:1];
}

希望这会有所帮助。感谢

答案 1 :(得分:3)

我创建了一些额外的变量来帮助跟踪经过的时间:

  1. BOOL watchStart;
  2. NSTimeInterval pauseTimeInterval;
  3. 我设置了watchStart = NO和pauseTimeInterval = 0.0。

    我使用watchStart检查其是否为开始或暂停状态(对于我的IBAction),而在updateTimer中,我将timeInterval设置为pauseTimeInterval

    代码的关键部分是:

    _startDate = [_startDate dateByAddingTimeInterval:((-1)*(_pauseTimeInterval))]
    

    该行会将额外的timeInterval添加到startDate,以计算暂停的时间。这有点类似于“退后”及时添加以前记录的区间。

    -(void) updateTimer {
    
        NSDate *currentDate = [NSDate date];
    
        NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:_startDate];    
        NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    
    
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"mm:ss.S"];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    
        NSString *timeString = [dateFormatter stringFromDate:timerDate];
        _stopWatchLabel.text = timeString;
        _pauseTimeInterval = timeInterval;
    
    }
    
    
    
    -(IBAction)btnStartPause:(id)sender {
    
        if(_watchStart == NO) {
            _watchStart = YES;
            _startDate = [NSDate date];
            _startDate = [_startDate dateByAddingTimeInterval:((-1)*(_pauseTimeInterval))];
            _stopWatchTime = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
        }
        else {
            _watchStart = NO;
            [_stopWatchTime invalidate];
            _stopWatchTime = nil;
            [self updateTimer];
        }
    

答案 2 :(得分:1)

NSTimer没有暂停或恢复方法。您可以制作两种类型的计时器,一种只实现一次,另一种只重复一次。例如:

创建一个将每秒输入回调myMethod的计时器。

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1 
    target:self 
    selector:@selector(myMethod:) 
    userInfo:nil 
    repeats:YES];

你可能会选择这个为你的目的,你班上应该保留一些

BOOL pausevariable并在回调myMethod中执行以下操作:

 - (void) myMethod:(NSTimer *) aTimer
{
     if (!pause) {
       // do something
       // update your GUI
     }
}

您在代码中更新暂停的位置。要停止计时器并释放内存,请致电

 [myTimer invalidate];
希望这会有所帮助。

答案 3 :(得分:0)

上述例子的小修正:

_startDate = [_startDate dateByAddingTimeInterval:((-1)*(_pauseTimeInterval))];

添加retain @ the end:

_startDate = [[_startDate dateByAddingTimeInterval:((-1)*(_pauseTimeInterval))]retain];

这会让事情变得更好: - )

答案 4 :(得分:0)

-(void)startStopwatch
{

//initialize the timer HUD
[self setSeconds:second];
// [self.hud.stopwatch setSeconds:_secondsLeft];

//schedule a new timer
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                          target:self
                                        selector:@selector(tick:)
                                        userInfo:nil
                                         repeats:YES];
}

-(void)pause{

 [_timer invalidate];
}

-(void)resume {

 [_timer isValid];

}

使用此代码我们可以暂停和恢复计时器

答案 5 :(得分:0)

朋友我成功实现了iOs计时器app的暂停和恢复功能,代码如下

- (IBAction)pauseT:(id)sender {
se = sec;
mi = min;
ho = hour;
[timer invalidate];

}

- (IBAction)resumeT:(id)sender {
sec = se;
min = mi;
hour = ho;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];

}

希望这对你们有用..