xcode 如何重置 NSTimer?SWIFT代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31690634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reset NSTimer? swift code
提问by LuKenneth
So I'm creating an app/game where you tap a button corresponding to a picture before the timer runs out and you lose. You get 1 second to tap the button, and if you choose the right button then the timer resets and a new picture comes up. I'm having trouble reseting the timer. It fires after one second even after I attempt to reset it. Here's the code:
所以我正在创建一个应用程序/游戏,您可以在计时器用完之前点击与图片对应的按钮,然后您就输了。您有 1 秒钟的时间点击按钮,如果您选择正确的按钮,则计时器将重置并出现新图片。我在重置计时器时遇到问题。即使我尝试重置它,它也会在一秒钟后触发。这是代码:
loadPicture() runs off viewDidLoad()
loadPicture() 在 viewDidLoad() 之外运行
func loadPicture() {
//check if repeat picture
secondInt = randomInt
randomInt = Int(arc4random_uniform(24))
if secondInt != randomInt {
pictureName = String(self.PicList[randomInt])
image = UIImage(named: pictureName)
self.picture.image = image
timer.invalidate()
resetTimer()
}
else{
loadPicture()
}
}
and here's the resetTimer() method:
这是 resetTimer() 方法:
func resetTimer(){
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("gameOverTimer"), userInfo: nil, repeats: false)
}
I think it may have something to do with NSRunloops? I'm not sure. I don't even know what a NSRunloop is to be honest.
我认为这可能与 NSRunloops 有关?我不知道。老实说,我什至不知道 NSRunloop 是什么。
回答by LuKenneth
So I finally figured it out...
所以我终于明白了...
I had to make a separate function to start the timer by initializing it. And in the resetTimer() function I added the timer.invalidate() line. So my code looks like this:
我必须创建一个单独的函数来通过初始化它来启动计时器。在 resetTimer() 函数中,我添加了 timer.invalidate() 行。所以我的代码是这样的:
func loadPicture() {
//check if repeat picture
secondInt = randomInt
randomInt = Int(arc4random_uniform(24))
if secondInt != randomInt {
pictureName = String(self.PicList[randomInt])
image = UIImage(named: pictureName)
self.picture.image = image
resetTimer()
}
else{
loadPicture()
}
}
func startTimer(){
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("gameOverTimer"), userInfo: "timer", repeats: true)
}
func resetTimer(){
timer.invalidate()
startTimer()
}
EDIT
编辑
With the new selector syntax it looks like this:
使用新的选择器语法,它看起来像这样:
func startTimer(){
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(NameOfClass.startTimer), userInfo: "timer", repeats: true)
}