The issue is that exerciseTime[value]
never changes, so the view is not redrawn.
Even though exerciseTime[value].timeIntervalSinceNow
might be different, the actual exerciseTime[value]
remains constant.
I recommend you use a Timer
with an ObservableObject
instead:
import Combine
import SwiftUI
class TimerViewModel: ObservableObject {
private var timer: AnyCancellable?
@Published var currentDate = Date()
func start(endDate: Date) {
timer = Timer.publish(every: 1.0, on: .main, in: .default)
.autoconnect()
.sink { [weak self] in
guard let self = self else { return }
self.currentDate = $0
if self.currentDate >= endDate {
self.timer = nil
}
}
}
}
and use it in your view:
struct TestView: View {
@State private var exerciseTime = Calendar.current.date(byAdding: .second, value: 15, to: Date())!
@StateObject private var timer = TimerViewModel()
var body: some View {
Group {
if timer.currentDate < exerciseTime {
Text(exerciseTime, style: .relative)
} else {
Text("0 sec")
}
}
.foregroundColor(.white)
.font(.largeTitle)
.padding(.top, 30)
.onAppear {
timer.start(endDate: exerciseTime)
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…