SwiftUI - 计时器不会在 0 处停止



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

我遵循了这个教程

@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)
}
}

最新更新