iPhone:如何编写减少倒数计时器的代码?
我想使用 UILabel
显示倒计时器,该计时器从 5 开始,每秒减少 1,例如:
5 4 3 2 1
,最后在达到 0 时隐藏标签。
我尝试使用 NSTimer SchedulerWithTimeInterval 对其进行编码,但惨败。
请帮我。
I want to show a countdown timer using a UILabel
which will start from 5 and reduces by 1 every second like:
5
4
3
2
1
and finally hides the label when it reaches 0.
I tried to code it using NSTimer scheduledTimerWithTimeInterval
but failed miserably.
Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只是在做类似的事情。我的代码中有一个名为 timeReamin 的 UILabel。它每秒更新一次,直到达到 0,然后显示警报。我必须警告您,由于计时器与您的 UI 在同一线程上运行,因此您可能会遇到一些抖动。我还没有解决这个问题,但这适用于简单的计时器。这是我正在使用的代码:
找到了一个消除抖动的线程解决方案。在 viewDidLoad 方法或 applicationDidFinishLaunching 中,您需要一行,例如:
这将使用 createTimer 方法启动一个线程。但是,您还需要更新 createTimer 方法:
其中大部分是标准线程入口例程的内容。池用于线程所采用的托管内存策略。如果您使用垃圾收集,则不需要这样做,但这并没有什么坏处。 runloop 是一个事件循环,每秒持续执行一次,以在时间流逝时生成事件。主线程中有一个自动创建的运行循环,这是一个特定于这个新线程的运行循环。然后注意最后有一个新语句:
这确保了线程将无限期地执行。您可以管理计时器,例如重新启动计时器或在其他方法中将其设置为不同的值。我在代码中的其他位置初始化了计时器,这就是该行已被删除的原因。
I was just doing something like that. I have a UILabel that is called timeReamin in my code. It's updated every second until it reaches 0 and then an alert is displayed. I must warn you that since the timer runs on the same thread as your UI, you may experience some jitter. I have not solved that problem yet, but this works for simple timers. Here is code that I am using:
Figured out a threaded solution that removes the jitter. In the viewDidLoad method or applicationDidFinishLaunching, you need a line such as:
This will launch a thread using the createTimer method. However, you also need to update the createTimer method as well:
Most of this is standard thread entry routine stuff. The pool is used for managed memory strategies employed by the thread which. This is not needed if you are using garbage collection, but it does not hurt. The runloop is an event loop that is executed continuously to generate the events when the time elapses every second. There is a runloop in your main thread that is created automatically, this is a runloop that is specific to this new thread. Then notice that there is a new statement at the end:
This ensures that the thread will execute indefinitely. You can manage the timer, such as restarting it or setting it for different values within the other methods. I initialize my timer at other places in my code and that is why that line has been removed.
这是使用 ScheduledTimerWithTimeInterval 的示例。使用:
在您的 .h 中:
在您的 .m 中
Here is an example using scheduledTimerWithTimeInterval. To use:
In your .h:
In your .m
这是倒计时器的最终解决方案。您还可以使用来自 Web 服务的开始和结束日期,也可以使用当前系统日期。
This is the final solution for countdown timer. You can also use start and end dates comming from the web service or you can also use current system date.