Search code examples
swiftxcodetimerconditional-statementsinvalidation

Swift question, how to stop my timer at 00:00 not negative number


I am wondering how to stop my simple timer at 00:00.

I added on my conditional statements "else if seconds < 0 then invalidate()"

However, it stops at 00.-1.

As a beginner I think I missed some simple syntax or logic.

I need your generous favour.

Thank you :)

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var showTime: UILabel!

    var timer = Timer()
    var timeSet = 0

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func buttonToSet(_ sender: UIButton) {

        stopTimer()
        timeSet += 5
        timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector: #selector(setTimer), userInfo:nil, repeats: true)

    }

    @IBAction func buttonToReset(_ sender: UIButton) {

        stopTimer()
        timeSet = 0
        showTime.text = "00:00"

    }

    @objc func setTimer() {

        let seconds = timeSet % 60
        var secondsString = "\(seconds)"
        let minutes = timeSet / 60
        var minutesString = "\(minutes)"

        if seconds < 10 && seconds >= 0 {
            secondsString = "0\(seconds)"
        } else if seconds < 0 {
            timer.invalidate()
        }


        if minutes < 10 {
            minutesString = "0\(minutes)"
        }

        showTime.text = "\(minutesString):\(secondsString)"
        timeSet -= 1

    }

    func stopTimer() {
        timer.invalidate()
    }

}

Solution

  • Update your condition ... Currently when second goes below 0 .. then timer is invalidating ...

     if seconds < 10 && seconds >= 0 {
         secondsString = "0\(seconds)"
    
             if seconds == 0 {
                timer.invalidate()
    
                }
            }