简体   繁体   English

倒数计时器 SwiftUI

[英]Countdown timer SwiftUI

How to make a countdown timer daily at a specific time.如何每天在特定时间制作倒数计时器。 When I open the application again, the timer is reset and the countdown starts again, I'm trying to figure out how to make the timer start again after its time has elapsed..当我再次打开应用程序时,计时器被重置并且倒计时再次开始,我试图弄清楚如何让计时器在它的时间过去后再次启动..

For example, so that this timer starts over every day at 6 pm例如,让这个计时器在每天下午 6 点重新开始

struct TimerView: View {
    //MARK: - PROPERTIES
    @State var timeRemaining = 24*60*60
    
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    //MARK: - BODY
    var body: some View {
        
        Text("\(timeString(time: timeRemaining))")
            .font(.system(size: 60))
            .frame(height: 80.0)
            .frame(minWidth: 0, maxWidth: .infinity)
            .foregroundColor(.white)
            .background(Color.black)
            .onReceive(timer){ _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }else{
                    self.timer.upstream.connect().cancel()
                }
            }
    }
    
    //Convert the time into 24hr (24:00:00) format
    func timeString(time: Int) -> String {
        let hours   = Int(time) / 3600
        let minutes = Int(time) / 60 % 60
        let seconds = Int(time) % 60
        return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
    }
}

the timer is reset and the countdown starts again计时器重置,倒计时再次开始

You could try to play with UserDefaults to store variables in the device's memory.您可以尝试使用 UserDefaults 将变量存储在设备的 memory 中。

Here is the Documentation: https://developer.apple.com/documentation/foundation/userdefaults这是文档: https://developer.apple.com/documentation/foundation/userdefaults

Take a look at TimelineView and AppStorage eg看看TimelineViewAppStorage例如

@AppStorage("StartDate") var startDate: Date
...
TimelineView(.periodic(from: startDate, by: 1)) { context in
    AnalogTimerView(date: context.date)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM