在特定时间内移动滑块
我有一个带有 96 个插槽的滑块,我需要在 60 秒内将滑块从 0 逐步移动到 95。我应该使用间隔 (60/96) 和 96 次重复的 NSTimer 还是有更好的解决方案?
I have a slider with 96 slots and I need to moves slider step by step from 0 to 95 in 60 seconds. Should I use NSTimer with interval (60/96) and 96 repeats or there is a better solution for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能是最好的方法。
NSTimer
在该时间间隔内的行为应该相当一致,只有在大约每 1/10 秒或更快地调用它时,它才会开始变得不可靠。但是,如果它的行为与您希望的不一样,请做一些解释:
它不会是完美的,因为
NSTimer
没有字面上的滴答事件 > 每个间隔。相反,NSTimer
受其线程运行循环的支配,直到其间隔到期后一段时间,它可能才开始调用您的@selector
方法。然后将其与调用屏幕更新相结合,这也不是锁步的。它的准确性主要取决于您在运行循环中所做的其他事情......如果您设备的小大脑中没有发生太多事情,那么您的滑块应该看起来像您希望的那样移动。
编辑:您还可以考虑具有较长间隔的 NSTimer,并使用 UIView 的 animateWithDuration... 方法使其显得平滑?
That's probably the best approach. The
NSTimer
should behave fairly consistently at that interval, it only starts to get unreliable when calling it around every 1/10th second, or faster.However, a bit of explanation in case it doesn't quite behave as you'd hoped:
It won't be perfect because the
NSTimer
doesn't have it's tick event literally every interval. Rather, theNSTimer
is at the mercy of it's thread's run-loop, which may not get around to calling your@selector
method until a while after its interval has expired. Then combine that with calling for screen updates which are also not lock-step.It's accuracy will mostly depend on what else you're doing in your run-loop... if there's not much going on in your device's little brain, then your slider should appear to move just as you'd hoped.
Edit: You may also consider an NSTimer with a longer interval, and use the UIView's animateWithDuration... methods to make it appear smooth?