-1

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

我已经尝试过[NSTimer scheduledTimerWithTimeInterval]但无法使其正常工作,但也怀疑这是实现此目的的理想方式。

4

3 回答 3

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.
}
于 2012-09-12T12:32:41.887 回答
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

于 2012-09-12T12:29:35.483 回答
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
于 2012-09-12T12:36:10.927 回答