我在互联网上搜索了答案,但一无所获。我试过了
- (void)viewDidLoad {
[super viewDidLoad];
twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer) userInfo:nil repeats:YES]; }
- (void)timer {
for (int totalSeconds = 120; totalSeconds > 0; totalSeconds--){
timerLabel.text = [self timeFormatted:totalSeconds];
if ( totalSeconds == 0 ) {
[twoMinTimer invalidate];
} } }
但它没有用,当我转到那个 View 时,标签从 2.00 变为 0.01,然后就停止了。
任何建议将不胜感激 - 菲利普
最佳答案
您使用的是一次性 for 循环,而不是简单地减少总时间。试试这个:
- (void)viewDidLoad {
[super viewDidLoad];
totalSeconds = 120;
twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timer)
userInfo:nil
repeats:YES];
}
- (void)timer {
totalSeconds--;
timerLabel.text = [self timeFormatted:totalSeconds];
if ( totalSeconds == 0 ) {
[twoMinTimer invalidate];
}
}
将 totalSeconds
声明为 int。
编辑:非常感谢@JoshCaswell 和@MichaelDorst 分别提供的建议和代码格式。 NSTimer 绝不是时间的准确表示,对于秒表或计数器来说绝对不够准确。相反,NSDate 的 +dateSinceNow
将是一个更准确的替代品,甚至逐渐降低级别的 CFAbsoluteTimeGetCurrent()
和 mach_absolute_time()
也可以准确到 sub -毫秒
关于objective-c - Objective-C 如何制作一个从两分钟开始倒计时的计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11377616/