gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:30:24 25 4
gpt4 key购买 nike

我有一个计时器,可以从特定日期倒数到当前日期
但我面临的问题是计时器在到达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中设置计时器,并在timerendDate对齐时使currentDate无效。

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

关于ios - SwiftUI-计时器不会在0处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63149626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com