scheduledtimer scheduled example create ios swift nstimer

ios - example - Cómo detener NSTimer.scheduledTimerWithTimeInterval



timer.scheduledtimer swift 4 (3)

No tienes que usar Selector :

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

Además, el temporizador pasa al método seleccionado, por lo que puede invalidarlo dentro del método si necesita:

func updateTimer(timer: NSTimer) { timeLabel.text = String(Counter++) timer.invalidate() }

O si el temporizador es una variable de instancia:

myTimer.invalidate() myTimer = nil

Es bueno anular el temporizador de la variable de instancia después de haberlo invalidado, ya que evita la confusión adicional si necesita crear otro temporizador con la misma variable. Además, los nombres de los métodos y las variables deben comenzar con una letra minúscula.

Captura de pantalla para mostrar el temporizador invalidado y configurado en cero.

Actualización para Swift 2.2+

Consulte https://stackoverflow.com/a/36160191/2227743 para ver la nueva sintaxis #selector reemplaza a Selector() .

¿Cómo detengo el funcionamiento de mi temporizador? No como una pausa, sino una parada.

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() }

}

Puedo iniciar el temporizador, pero cuando presiono el botón Detener, se reinicia y comienza a contar nuevamente. No se detiene

Lo hizo funcionar. ¡Algo estaba buggy con mi proyecto! Se corrigió eliminando el botón y volviendo a agregarlos. Parece que tuve un duplicado o algo así.


puede usar esto cuando se cumple alguna condición y desea detener el temporizador:

Timer.invalidate()

Aquí está el ejemplo simple:

func UpdateTimer(){ timeLabel.text = String(Counter++) if timeLabel.text == String("5") { Timer.invalidate() } }

esto detendrá el temporizador.

Puede modificarlo según su necesidad.


Como pre Swift 2.2

let printTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(printDescription), userInfo: nil, repeats: true) func printDescription() { print("Print timer will print every after 2.0 seconds") }

El temporizador de impresión se imprimirá cada 2,0 segundos