创建 iOS 计时器

发布于 2024-11-24 08:42:07 字数 695 浏览 2 评论 0原文

我正在尝试创建“秒表”类型的功能。我有一个标签(用于显示经过的时间)和两个按钮(启动和停止计时器)。开始和停止按钮分别调用 startTimerstopTimer 函数。计时器每秒触发并调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心凉怎暖 2024-12-01 08:42:07

有点过时,但如果有人仍然感兴趣......

不要“停止”计时器,而是在暂停期间停止递增,例如

- (void)increaseTimerCount
{
   if (!self.paused){
      timerCount++
   }

   timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount];
}

A bit dated but if someone is still interested...

don't "stop" the timer, but stop incrementing during pause, e.g.

- (void)increaseTimerCount
{
   if (!self.paused){
      timerCount++
   }

   timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount];
}
咿呀咿呀哟 2024-12-01 08:42:07

如果不使用 invalidate,则无法暂停计时器。您可以做的是

[timer fire];

startTimer 中创建计时器后添加。

You can't pause the timer without using invalidate. What you can do is add

[timer fire];

after you create the timer in startTimer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文