I need to create a simple stopwatch in Swift using the method timeIntervalSince(). I don't really understand how to use timeIntervalSince (what I need and how to implement it) and how to transform it into a String that will show me the passed time like "00:00:00".
I know I need to use a Timer to update the Label and invalidate it when clicking on "Stop".
I'd really appreciate any help on this. Let me know if you need more information.
CodePudding user response:
The method timeIntervalSince(_:)
is a method of Date
. It gives you the number of seconds that have passes since some other date and the date you are asking.
So,
Create a StopwatchVC.
Give StopwatchVC a startTime
var of type Date.
Also give it a Timer
var. Lets call that updateTimer
.
When the user taps the start button, save Date()
(the time right now) into startTime. Also start a repeating timer, updateTimer
that fires every 1/10 second. (or however often you want to update your stopwatch, but note that faster than 1/60 is pointless because the screen can't update any faster than that, and timers are only accurate to about 1/50 sec anyway.)
Each time updateTimer
fires, calculate the number of seconds that have elapsed since the start time and display it to the screen:
let seconds = Date().timeIntervalSince(startTime)
Date()
is the current date and time, with sub-millisecond accuracy.
Date().timeIntervalSince(startTime)
will give you the number of seconds since startTime
, again with sub-millisecond accuracy.
Format and display the elapsed time to the screen. You could use a DateComponentsFormatter
or build a time string yourself using a NumberFormatter, or even String(format:)
CodePudding user response:
//
// StopWatchVC.swift
// Gem
//
// Created by Macbook 5 on 4/18/22.
//
import UIKit
class StopWatchVC:UIViewController {
var timer:Timer?
var startTime = Date()
let titleLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(titleLabel)
titleLabel.frame = CGRect(x: 0, y: 0, width: 200, height: 60)
titleLabel.center = view.center
titleLabel.textColor = .red
view.backgroundColor = .white
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
let timeInterval = Date().timeIntervalSince(startTime)
titleLabel.text = timeInterval.stringFromTimeInterval()
}
}
extension TimeInterval{
func stringFromTimeInterval() -> String {
let time = NSInteger(self)
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
}