Formatting stopwatch's time in Swift

I'm trying to solve my problem with stopwatch. Every 10 seconds it's not zero at he end in seconds and no + 1minute after 60 seconds. time format should be m:ss (0:00). Start and Stop are same buttons in my app. Can u help me?

var timer: Timer?
var isStarted = false
var counter = 0.00

@objc func updateTimeLabel() {
        counter += 0.01
        timerLabel.text = String(round(counter*1000)/1000)
      }


@IBAction func startStopButtonDidTouch(_ sender: UIButton) {
        if isStarted { //When tapped STOP
            timer?.invalidate()
            isStarted = false
            locationManager.stopUpdatingLocation()
            startStopButton.setTitle("START", for: .normal)
       
      } else { //When tapped START
        locationManager.startUpdatingLocation()
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true)
        isStarted = true
        startStopButton.setTitle("STOP", for: .normal)
       
        }
  }

1 answer

  • answered 2020-11-20 14:53 vadian

    There is a date formatter to display time intervals as date components

    var counter : TimeInterval = 0
    
    let dateFormatter : DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.minute, .second]
        formatter.zeroFormattingBehavior = .pad
        return formatter
    }()
    
    @objc func updateTimeLabel() {
        counter += 1
        timerLabel.text = dateFormatter.string(from: counter)!
    }