0

这是我的问题,当我单击开始按钮时,计时器会运行,当我单击停止按钮时,它会停止。但是,当我单击开始按钮时,它会变回零。我希望开始按钮在计时器停止的地方继续。

.h

NSTimer *stopWatchTimer;
    NSDate *startDate;
    @property (nonatomic, retain) IBOutlet UILabel *stopWatchLabel;
    - (IBAction)onStartPressed;
    - (IBAction)onStopPressed;
    - (IBAction)onResetPressed;

.m

    - (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.SSS"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSString *timeString=[dateFormatter stringFromDate:timerDate];
    stopWatchLabel.text = timeString;
    }
    - (IBAction)onStartPressed {
    startDate = [NSDate date];
    // 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)onStopPressed {
    [stopWatchTimer invalidate];
    stopWatchTimer = nil;
    [self updateTimer];
    }
    - (IBAction)onResetPressed {
    stopWatchLabel.text = @”00:00:00:000″;
    }

请帮忙谢谢

4

1 回答 1

0

您在处理状态时遇到问题。一种状态是按下启动按钮,但之前没有按下复位按钮。另一种状态是启动按钮被按下,而在它之前已经按下复位按钮。您可以做的一件事是创建一个 iVar 来跟踪此状态。所以使用这样的 BOOL:

首先声明 iVar:

BOOL resetHasBeenPushed;

将值初始化为 NO。

然后这样做

 - (IBAction)onResetPressed {
    stopWatchLabel.text = @”00:00:00:000″;
    resetHasBeenPushed = YES;

现在您需要在某个时候将其设置回 NO,这可以在 start 方法中完成:

- (IBAction)onStartPressed {
    startDate = [NSDate date];
    // 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];
    resetHasBeenPushed = NO;
}
    }

顺便说一句,如果你在 iVar 中制作你的 NSDateFormatter,你不需要重复初始化它。将以下行移至您的 inti 代码,或 osmewhere 它只运行一次:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

更新

试试这个:

- (IBAction)onStartPressed {
    if (resetHasBeenPushed== YES) {
        startDate = [NSDate date];  // This will reset the "clock" to the time start is set
    }

    // 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];
    }
于 2012-02-29T20:04:23.850 回答