Skip to content

Instantly share code, notes, and snippets.

@mps
Created December 17, 2021 19:02
Show Gist options
  • Save mps/626273abd9ab73152f1a784c195cb715 to your computer and use it in GitHub Desktop.
Save mps/626273abd9ab73152f1a784c195cb715 to your computer and use it in GitHub Desktop.
A little stopwatch
class Stopwatch: ObservableObject {
@Published private var progressTime = 58
var hours: String {
let time = progressTime / 3600
return time < 10 ? "0\(time)" : "\(time)"
}
var minutes: String {
let time = (progressTime % 3600) / 60
return time < 10 ? "0\(time)" : "\(time)"
}
var seconds: String {
let time = progressTime % 60
return time < 10 ? "0\(time)" : "\(time)"
}
var elapsedTime: String {
hours + ":" + minutes + ":" + seconds
}
private var timer: Timer?
func start() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in
self.progressTime += 1
})
}
func stop() {
timer?.invalidate()
}
}
struct ContentView: View {
@ObservedObject var stopwatch: Stopwatch = Stopwatch()
var body: some View {
VStack {
Text(stopwatch.elapsedTime)
.padding()
}.onAppear() {
stopwatch.start()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment