如何停止NSTimer.scheduledTimerWithTimeInterval

Eri*_*une 39 nstimer ios swift

如何阻止我的计时器运行?不是暂停,而是停顿.

import UIKit

class LastManStandingViewController: UIViewController {    

@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var timeTextbox: UITextField!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var stopButton: UIButton!

var myCounter = 0
var myTimer : NSTimer = NSTimer()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    timeLabel.text = String(myCounter)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func startTimer(){
    myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true)
    println("func startTimer")
}

func stopTimer(){
    myTimer.invalidate()
    myCounter = 0
    timeLabel.text = String(myCounter)
    println("func stopTimer")
}

func updateTimer(){
    timeLabel.text = String(myCounter++)
    println("func updateTimer")
}
@IBAction func startButton(sender: AnyObject) {
    startTimer()
}
@IBAction func stopButton(sender: AnyObject) {
    stopTimer()
}
Run Code Online (Sandbox Code Playgroud)

}

我可以启动计时器,但是当我按下"停止"按钮时,它会自动重置,然后重新开始计数.它不会停止.

使它工作.我的项目出了点问题!通过删除按钮并重新添加它来修复它.看起来我有重复或什么的.

aya*_*aio 77

你不必使用Selector:

@IBAction func startButton(sender: AnyObject) {
    myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer:", userInfo: nil, repeats: true)
}
Run Code Online (Sandbox Code Playgroud)

此外,计时器将自身传递给所选方法,因此如果您需要,可以在方法内使其无效:

func updateTimer(timer: NSTimer) {
    timeLabel.text = String(Counter++)
    timer.invalidate()
}
Run Code Online (Sandbox Code Playgroud)

或者,如果计时器是实例变量:

myTimer.invalidate()
myTimer = nil
Run Code Online (Sandbox Code Playgroud)

nil使实例变量计时器无效后,它是一件好事,如果你需要使用相同的变量创建另一个计时器,它可以避免进一步的混淆.此外,方法名称和变量应以小写字母开头.

屏幕截图显示计时器无效并设置为nil.

截图

Swift 2.2+的更新

有关新语法替换,请参阅/sf/answers/2531213401/.#selectorSelector()


Dha*_*esh 7

你可以在满足某些条件并且想要停止计时器时使用它:

Timer.invalidate()
Run Code Online (Sandbox Code Playgroud)

这是一个简单的例子:

func UpdateTimer(){
    timeLabel.text = String(Counter++)
    if timeLabel.text == String("5") {
        Timer.invalidate()
    }
}
Run Code Online (Sandbox Code Playgroud)

这将停止计时器.

您可以根据需要进行修改.