首先,我是 Swift 编程的新手,请耐心等待!我正在使用 Swift 为 iOS 制作 PONG(经典游戏,我相信你已经听说过)。我想让游戏球在屏幕上移动。现在在 VB 中(这是我以前编写代码的方式),我只需将一个计时器拖到 View 中,设置一个间隔并编写类似 ball.top - 5
的内容
在它自己的个人潜艇中。不过,我真的不知道如何在 Swift 中解决这个问题,我已经做到了:NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerDidFire:", userInfo: nil, repeats: true)
但我不知道这是做什么的,也不知道在哪里编写每次计时器触发时要执行的代码。我还需要知道如何启用和禁用定时器!!
非常感谢您的帮助!
最佳答案
首先,您需要编写一个与您的选择器同名的函数(顺便说一下,我想创建一个这样的选择器会更好:Selector("timerDidFire:")
,所以你的计时器看起来像 timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("timerDidFire:"), userInfo: nil, repeats: true)
)。正如我之前所说,现在您需要编写函数:
func timerDidFire(timer: NSTimer) {
// something that will be executed each time the timer fires
}
计时器将在这段代码之后立即启动:timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerDidFire:", userInfo: nil, repeats: true)
将被执行。
要禁用计时器,只需在需要的地方写入 timer.invalidate()
。
为整个类制作一个计时器也更好,为此你需要在类定义后的花括号后面编写 var timer = NSTimer()
(class ... : . .. {
).我相信这会对您有所帮助,但没有什么比阅读 swift 文档更好的了。
关于ios - 在 Swift 中使用定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27900347/