簡體   English   中英

倒數計時器 SwiftUI

[英]Countdown timer SwiftUI

如何每天在特定時間制作倒數計時器。 當我再次打開應用程序時,計時器被重置並且倒計時再次開始,我試圖弄清楚如何讓計時器在它的時間過去后再次啟動..

例如,讓這個計時器在每天下午 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)
    }
}

計時器重置,倒計時再次開始

您可以嘗試使用 UserDefaults 將變量存儲在設備的 memory 中。

這是文檔: https://developer.apple.com/documentation/foundation/userdefaults

看看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