SwiftUI - 计时器不会停在 0

SwiftUI - Timer doesn't stop at 0

我有一个计时器,可以从特定日期倒计时到当前日期 但我面临的问题是计时器在到达 00:00:00

时不会停止

我关注了这个tutorial

@State var currentDate: Date = Date()
var timer: Timer {
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (_) in
        self.currentDate = Date()
    }
}

var endDate = Calendar.current.date(byAdding: .minute, value: 1, to: Date())!

var body: some View {
    Text(countdownString(to: endDate))
        .font(.headline)
        .fontWeight(.bold)
        .foregroundColor(.green)
        .onAppear {
            _ = self.timer
            if self.endDate == self.currentDate {
                self.timer.invalidate()
            }
    }
}



func countdownString(to date: Date) -> String {
    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents([.hour, .minute, .second], from: currentDate, to: endDate)
    return String(format: "%02d hours : %02d minutes : %02d seconds",
                  components.hour ?? 00,
                  components.minute ?? 00,
                  components.second ?? 00)
}

onAppear中设置定时器并在endDatecurrentDate对齐时使timer无效。

struct CV: View {
    @State var currentDate: Date = Date()
    @State var timer: Timer?

    var endDate = Calendar.current.date(byAdding: .minute, value: 1, to: Date())!

    var body: some View {
        Text(countdownString(to: endDate))
            .font(.headline)
            .fontWeight(.bold)
            .foregroundColor(.green)
            .onAppear {
                self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
                    self.currentDate = Date()
                }
        }
    }

    func countdownString(to date: Date) -> String {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents([.hour, .minute, .second], from: currentDate, to: endDate)
        if currentDate >= endDate {
            timer?.invalidate()
            timer = nil
        }
        return String(format: "%02d hours : %02d minutes : %02d seconds",
                      components.hour ?? 00,
                      components.minute ?? 00,
                      components.second ?? 00)
    }
}