秒表计数2
我在Objective-C中制作一个秒表:
- (void)stopwatch { NSInteger hourInt = [hourLabel.text intValue]; NSInteger minuteInt = [minuteLabel.text intValue]; NSInteger secondInt = [secondLabel.text intValue]; if (secondInt == 59) { secondInt = 0; if (minuteInt == 59) { minuteInt = 0; if (hourInt == 23) { hourInt = 0; } else { hourInt += 1; } } else { minuteInt += 1; } } else { secondInt += 1; } NSString *hourString = [NSString stringWithFormat:@"%d", hourInt]; NSString *minuteString = [NSString stringWithFormat:@"%d", minuteInt]; NSString *secondString = [NSString stringWithFormat:@"%d", secondInt]; hourLabel.text = hourString; minuteLabel.text = minuteString; secondLabel.text = secondString; [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES]; }
秒表有三个独立的标签,如果你想知道,几小时,几分钟和几秒钟。 但是,按1计数,就像2,4,8,16等
此外,代码的另一个问题(相当小)是它不显示所有数字作为两位数字。 例如,它将时间显示为0:0:1,而不是00:00:01。
任何帮助真的很感激! 我应该补充一点,我对Objective-C非常陌生,所以尽可能简单,谢谢!
不要使用repeats:YES
如果您在每次迭代中计划计时器,请执行repeats:YES
。
你在每次迭代中产生一个计时器,计时器已经在重复,导致计时器的指数级增长(因此调用stopwatch
的方法)。
将计时器实例更改为:
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:NO];
或者在stopwatch
方法之外启动它
对于第二个问题,只需使用适当的格式string。
NSString *hourString = [NSString stringWithFormat:@"%02d", hourInt]; NSString *minuteString = [NSString stringWithFormat:@"%02d", minuteInt]; NSString *secondString = [NSString stringWithFormat:@"%02d", secondInt];
%02d
将打印一个十进制数字填充0
秒,长度为2,这正是你想要的。
( 来源 )
对于第一个问题,而不是创build每个调用的计时器实例。删除线
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];
从function秒表。
用上面的行代替您的呼叫function秒表。 即replace
[self stopwatch]
同
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];