GabrielMSC GabrielMSC - 6 months ago 13
Swift Question

SWIFT: countdown from 3 to change label at 0

Here is my dilemma, I am making something very simple, just am doing some discovering. basically, I have a button, and a label, and I have the button set up to count down from 3, to 0, but I instead of it displaying 0, i want it to stop the countdown, and display a string that says "yes!"

Here is some code I've come up with.



class ViewController: UIViewController {

var myTimer: NSTimer = NSTimer()
var count: Int = 4

func startCountdown(){
myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(myUpdate), userInfo: nil, repeats: true)

}

func myUpdate() {
if(count > 0) {
count -= 1
timerLabel.text = "\(count)"
}
}

func countdownReachedZero(){
if count == 1{
myTimer.invalidate()
timerLabel.text = "Yes!"
}
}

@IBOutlet weak var resultButtonOutlet: UIButton!
@IBOutlet weak var timerLabel: UILabel!
@IBAction func resultButton(sender: AnyObject) {
//button actions, starts countdown from 3-1
startCountdown()

}


override func viewDidLoad() {
super.viewDidLoad()
countdownReachedZero()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}


}

currently, my result, is just a countdown from 3-0, and it just completely ignores the countdownReachedZero() call from viewDidLoad.
if I impliment the countdownReachedZero() method inside the button, and press the button, wait for it to reach 0, then press the button again, it will change the text, but I am not sure where I am going wrong.

I've tried various methods. One I think would work, is a loop through a string that just displays them in order for a certain amount of time, yet I lack knowledge for that either.

is there something more simple? am I missing something?

if you need anything else, I can provide.

Answer

The problem is that this function is missing half its logic:

func myUpdate() {
    if(count > 0) {
        count -= 1
        timerLabel.text = "\(count)"
    }
}

That code is called every time the timer fires. It says what to do if count > 0, but you have completely forgotten to say what to do in the crucial case where count == 0!