Search code examples
iosswiftnstimer

Label not showing value of timer in Swift


I have a timer loop that executes a basic countdown and it prints the value to the console. I'm trying to have that value set to a text value of a label. Even though the Xcode console shows the correct countdown of the timer value, the label in the application still shows 0. Any ideas as to why this is happening? Here is the relevant code:

import UIKit

class GameViewController: UIViewController {

    @IBOutlet weak var timerLabel: UILabel!

    var timerCount = 7
    var timerRunning = false
    var timer = NSTimer()

    override func viewDidLoad() {
        super.viewDidLoad()

       self.timerCount = 7

       self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting"), userInfo: nil, repeats: true)

}

func Counting(){

        timerCount = 7

        do {

            println(timerCount)
            timerRunning = true
            --timerCount
            timerLabel.text = "\(timerCount)"
            println(timerCount)

        } while timerCount > 0

    }

Solution

  • The method Counting() is wrong.

    Every second you are launching the counting method and within that method you have a loop which updates the timerLabel.text, but the UI is not updated until the Counting() finishes...that's why is always showing 0. You need just to decrease the counting every second and update the label.

    I think this is what you need:

    func Counting(){
    
      if timerCount == 0
      {
        timerCount = 7 // or self.timer.invalidate() in case you want to  stop it
      }        
      else
      {
         timerCount--;
         timerLabel.text = "\(timerCount)"
         println(timerCount)
      }
    }
    

    Hope it helps