67 lines
1.6 KiB
Swift
67 lines
1.6 KiB
Swift
//
|
|
// SimpleStopWatch.swift
|
|
// WorkoutsPlus
|
|
//
|
|
// Created by Felix Förtsch on 12.09.24.
|
|
//
|
|
import SwiftUI
|
|
|
|
struct SimpleStopWatch: View {
|
|
@State var startDate: Date
|
|
@Binding var duration: TimeInterval
|
|
|
|
@State private var isPaused = false
|
|
@State private var timeString: String = "00:00:00"
|
|
@State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
|
|
|
|
var body: some View {
|
|
Text(timeString)
|
|
.onReceive(timer) { _ in
|
|
if !isPaused {
|
|
duration += 1
|
|
timeString = format(time: duration)
|
|
}
|
|
}
|
|
.onTapGesture {
|
|
isPaused.toggle()
|
|
}
|
|
.onAppear() {
|
|
duration = Date().timeIntervalSince(startDate)
|
|
timeString = format(time: duration)
|
|
startTimer()
|
|
}
|
|
.onDisappear() {
|
|
stopTimer()
|
|
}
|
|
}
|
|
|
|
private func stopTimer() {
|
|
timer.upstream.connect().cancel()
|
|
}
|
|
|
|
private func startTimer() {
|
|
timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
|
|
}
|
|
|
|
private func format(time: TimeInterval) -> String {
|
|
let totalTimeInSeconds = Int(time)
|
|
|
|
let hours = totalTimeInSeconds / 3600
|
|
let minutes = (totalTimeInSeconds % 3600) / 60
|
|
let seconds = totalTimeInSeconds % 60
|
|
|
|
var formattedTime = ""
|
|
if hours > 0 {
|
|
formattedTime += String(format: "%d:", hours)
|
|
}
|
|
formattedTime += String(format: "%02d:%02d", minutes, seconds)
|
|
|
|
return formattedTime
|
|
}
|
|
}
|
|
|
|
#Preview {
|
|
@Previewable @State var duration = 0.0
|
|
SimpleStopWatch(startDate: Date.now, duration: $duration)
|
|
}
|