Reputation: 285
Does anyone know how I can tell the timer to stop when it reaches 0. Right now it keeps counting down below zero.
import UIKit
class ViewController: UIViewController {
var timerCount = 20
var timerRunning = false
var timer = NSTimer()
@IBOutlet weak var timerLabel: UILabel!
func Counting() {
timerCount -= 1
timerLabel.text = "\(timerCount)"
}
@IBAction func startButton(sender: UIButton) {
if timerRunning == false {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector ("Counting"), userInfo: nil, repeats: true)
timerRunning = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if timerCount == 0 {
timerRunning = false
}
}
}
Upvotes: 0
Views: 3523
Reputation: 34945
Also, some additional advice: keep local state to a minimum. You can get rid of the timerRunning
variable because that state is already in the NSTimer
via its valid
property.
It simplifies code and results in less state errors if there is only a single place there you look.
Upvotes: 3
Reputation: 2130
Change your Counting
function to this:
func Counting() {
timerCount -= 1
timerLabel.text = "\(timerCount)"
if timerCount == 0 {
timer.invalidate()
timerRunning = false
}
}
From the NSTimer documentation:
Stopping a Timer
invalidate()
Stops the receiver from ever firing again and requests its removal from its run loop.
Discussion
This method is the only way to remove a timer from an NSRunLoop object. The NSRunLoop object removes its strong reference to the timer, either just before the invalidate method returns or at some later point.
If it was configured with target and user info objects, the receiver removes its strong references to those objects as well.
Special Considerations
You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.
Upvotes: 6