// // TimerView.swift // WorkoutsPlus // // Created by Felix Förtsch on 12.09.24. // import SwiftUI struct TimerView: View { @Binding var isActive: Bool @State private var time = 0 var startDate: Date? let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() var body: some View { Text("\(time)") .onReceive(timer) { _ in if isActive { if let startDate = startDate { self.time = Int(Date.now.timeIntervalSince(startDate)) } else { self.time += 1 } } } .onDisappear { self.timer.upstream.connect().cancel() } } } #Preview { TimerView(isActive: .constant(true), startDate: Date().addingTimeInterval(-3600)) // Example startDate 1 hour ago } #Preview { TimerView(isActive: .constant(true)) }