【发布时间】:2016-02-18 07:30:42
【问题描述】:
我正在使用NSTimer 在录制时在标签上显示秒数。
我在点击录制按钮时启动计时器,并在点击停止按钮时停止它。
当我点击播放按钮时,计时器没有重新启动。
-(void)startTimer
{
playTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timerController)
userInfo:nil
repeats:YES];
}
- (NSString*)getTimeStr : (int) secondsElapsed
{
seconds = secondsElapsed % 60;
int minutes = secondsElapsed / 60;
int hours = secondsElapsed/3600;
return [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
- (void)timerController{
seconds++;
[[self timeLabel] setText:[self getTimeStr:(seconds)]];
}
- (IBAction)recordTapped:(id)sender {
[self startTimer];
}
- (IBAction)stopTapped:(id)sender {
[playTimer invalidate];
playTimer=nil;
_timeLabel.text=@"00:00:00";
}
- (IBAction)playTapped:(id)sender {
[self startTimer];
}
【问题讨论】:
-
要重新启动计时器,您应该在
startTimer函数的开头将seconds变量重置为0 -
感谢您的完美工作。
-
只是我注意到我的计时器只运行了 1 分钟。之后它又从 00:00:01 开始。你能帮我解决这个问题吗
-
我忽略了另一个错误。您在
getTimeStr:函数中重用了变量seconds,这使得seconds变量始终小于或等于59。将seconds替换为int sec,当然,更改最后一行中的变量函数的sec以及 -
好的,我在一个小错误中失败了。现在工作正常
标签: ios objective-c nstimer