我有一个NSDate,我如何显示一个自动更新显示计时器的秒表?

时间:2012-09-12 12:27:32

标签: objective-c ios timer nsdate stopwatch

我有一个NSDate变量。从该变量中,我如何能够在视图中显示持续更新的秒表?

我已经尝试了[NSTimer scheduledTimerWithTimeInterval],但无法让它发挥作用,但也怀疑这是理想的做法。

3 个答案:

答案 0 :(得分:3)

NSTimer有什么问题?

- (void)startTimer {
    [NSTimer scheduledTimerWithTimeInterval:1/30.0f
                                     target:self
                                   selector:@selector(timerFired:)
                                   userInfo:[NSDate date]
                                    repeats:YES];
}

- (void)timerFired:(NSTimer *)timer {
    NSDate *startDate = timer.userInfo;
    NSTimeInterval secondsPassed = -[startDate timeIntervalSinceNow];
    // Update your label here.
}

答案 1 :(得分:2)

尝试

- (void)updateTimer
{
    static NSInteger counter = 0;
    [stopWatchLabel setText:[NSString stringWithFormat:@"Counter: %i", counter++]];
}

- (IBAction)onStartPressed:(id)sender {
    startDate = [[NSDate date]retain];

    // Create the stop watch timer that fires every 10 ms
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                                      target:self
                                                    selector:@selector(updateTimer)
                                                    userInfo:nil
                                                     repeats:YES];
}

您必须将IBAction连接到一个按钮,并将stopWatchLabel连接到界面构建器中的UILabel。

发现于:http://www.apptite.be/tutorial_ios_stopwatch.php

答案 2 :(得分:1)

我试过这个,它的工作

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];

-(void)timerCallback{
    NSDate *date=[NSDate date];
    NSLog(@"%@",date);
}

将timeInterval参数更新为你想要的,并在视图中显示它(我刚刚打印了日志);

我收到了这个日志:

2012-09-12 18:04:11.252 S[19550:f803] 2012-09-12 12:34:11 +0000
2012-09-12 18:04:12.170 S[19550:f803] 2012-09-12 12:34:12 +0000
2012-09-12 18:04:13.170 S[19550:f803] 2012-09-12 12:34:13 +0000
2012-09-12 18:04:14.170 S[19550:f803] 2012-09-12 12:34:14 +0000
2012-09-12 18:04:15.170 S[19550:f803] 2012-09-12 12:34:15 +0000
2012-09-12 18:04:16.170 S[19550:f803] 2012-09-12 12:34:16 +0000
2012-09-12 18:04:17.170 S[19550:f803] 2012-09-12 12:34:17 +0000
2012-09-12 18:04:18.170 S[19550:f803] 2012-09-12 12:34:18 +0000
2012-09-12 18:04:19.171 S[19550:f803] 2012-09-12 12:34:19 +0000
2012-09-12 18:04:20.170 S[19550:f803] 2012-09-12 12:34:20 +0000
2012-09-12 18:04:21.170 S[19550:f803] 2012-09-12 12:34:21 +0000