Home > Net >  resetting a swift timer
resetting a swift timer

Time:07-05

i have an app that uses a timer to make a simple stopwatch. however i am having trouble trying to reset the timer to zero. my resettingtimer function at the bottom of the code is dedicated to this. however i cannot set it back to zero because it is taking a string value.

//STOPWATCH UP SECTION---------
    func activateCountUpTimer() {
        timerCounting = true
        timerUp = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerCounter), userInfo: nil, repeats: true)
    }
    
    @IBAction func pauseCoutUpTimer(_ sender: Any) {
        
        if timerCounting == true {
            timerUp.invalidate()
            timerCounting = false
            //here to change the uibutton image from pause to reactivate when clicked
        } else {
            timerCounting = true
            timerUp = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerCounter), userInfo: nil, repeats: true)
        }
        
    }
    
    @objc func timerCounter() -> Void
    {
        count = count   1
        let time = secondsToHoursMinutesSeconds(seconds: count)
        let timeString = makeTimeString(hours: time.0, minutes: time.1, seconds: time.2)
        stopwatchLabel.text = timeString
    }
    
    func secondsToHoursMinutesSeconds(seconds: Int) -> (Int,Int,Int){
         return ((seconds / 3600), ((seconds % 3600)/60), ((seconds % 3600) % 60))
    }
    
    func makeTimeString(hours: Int, minutes: Int, seconds: Int) -> String {
        var timeString = ""
        timeString  = String(format: "d", hours)
        timeString  = " : "
        timeString  = String(format: "d", minutes)
        timeString  = " : "
        timeString  = String(format: "d", seconds)
        return timeString
    }
    
    func resettingtimer() {
        timerUp = 0
    }

    //END OF STOPWATCH SECTION---------

CodePudding user response:

Invalidate the timer with timerUp.invalidate(), set timerCounting to false, set count to zero, and set stopwatchLabel.text to zero.

  • Related