创建 iOS 计时器
我正在尝试创建“秒表”类型的功能。我有一个标签(用于显示经过的时间)和两个按钮(启动和停止计时器)。开始和停止按钮分别调用 startTimer
和 stopTimer
函数。计时器每秒触发并调用 increaseTimerCount
函数。我还有一个 ivar timerCount
,它以秒为单位保存经过的时间。
- (void)increaseTimerCount
{
timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount++];
}
- (IBAction)startTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(increaseTimerCount) userInfo:nil repeats:YES];
}
- (IBAction)stopTimer
{
[timer invalidate];
[timer release];
}
问题是,按下开始按钮时似乎有延迟(我假设这是由于每次调用 startTimer 时重新初始化计时器所致)。有没有办法只暂停和恢复计时器而不使其失效并重新创建它?或者更好/替代的方法?
谢谢。
I am trying to create a "stop watch" type functionality. I have one label (to display the elapsed time) and two buttons (start and stop the timer). The start and stop buttons call the startTimer
and stopTimer
functions respectively. Every second the timer fires and calls the increaseTimerCount
function. I also have an ivar timerCount
which holds on to the elapsed time in seconds.
- (void)increaseTimerCount
{
timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount++];
}
- (IBAction)startTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(increaseTimerCount) userInfo:nil repeats:YES];
}
- (IBAction)stopTimer
{
[timer invalidate];
[timer release];
}
The problem is that there seems to be a delay when the start button is pressed (which I am assuming is due to reinitializing the timer each time startTimer is called). Is there any way to just pause and resume the timer without invalidating it and recreating it? or a better/alternate way of doing this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有点过时,但如果有人仍然感兴趣......
不要“停止”计时器,而是在暂停期间停止递增,例如
A bit dated but if someone is still interested...
don't "stop" the timer, but stop incrementing during pause, e.g.
如果不使用
invalidate
,则无法暂停计时器。您可以做的是在
startTimer
中创建计时器后添加。You can't pause the timer without using
invalidate
. What you can do is addafter you create the timer in
startTimer
.