簡體   English   中英

SwiftUI - 定時器不在 0 處停止

[英]SwiftUI - Timer doesn't stop at 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)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM