Search code examples
swifttimerlabel

Automatic Running Timer


I am trying make a very simple countdown timer that is displayed on the screen without having to press a start button; continous. However, when I run the simulator only "Label" shows up on the screen with no countdown. I have my outlets correctly hooked up and am throwing no errors, and even following guides I can't figure what I am doing wrong. Any simple solutions?

Code:

class ViewController: UIViewController {


@IBOutlet weak var timerLabel: UILabel!


var seconds = 15
var timer = Timer()


func runTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector(("updateTimer")),userInfo: nil, repeats: true)
}

func updateTimer() {
    seconds -= 1
    timerLabel.text = String(seconds)
}






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

}


Solution

  • Change the selector syntax in this line first :

    func runTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer),userInfo: nil, repeats: true)
    }
    

    and add @objc to this func :

    @objc func updateTimer() {
        seconds -= 1
        timerLabel.text = String(seconds)
    }