这是我的问题,当我点击开始按钮时,计时器运行,当我点击停止按钮时,它停止。然而,当我点击"开始"按钮时,它会回到零。我希望启动按钮在计时器停止的地方继续。
.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″;
}
请帮忙感谢
您在处理状态时遇到问题。一种状态是启动按钮被按下,但重置按钮在它之前没有被按下。另一种状态则是启动按钮已被按下,重置按钮已在它之前被按下。你可以做的一件事是创建一个iVar来跟踪这种状态。所以使用这样的BOOL:
首先声明iVar:
BOOL resetHasBeenPushed;
将值初始化为NO。
然后进行
- (IBAction)onResetPressed {
stopWatchLabel.text = @”00:00:00:000″;
resetHasBeenPushed = YES;
现在,您需要在某个时刻将其设置回NO,这可能在启动方法中完成:
- (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,则不需要重复初始化它。在代码中移动以下行,或者在这里只运行一次:
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];
}