swift 更新关于真实的微小变化的视图

xienkqul  于 2023-11-16  发布在  Swift
关注(0)|答案(2)|浏览(116)

我试图更新视图的每一个真实的分钟的变化。我找不到任何通知发布者,可以触发,所以我有一个想法,启动计时器时,下一分钟的变化,但我真的不知道如何做到这一点(我已经尝试了这段代码,似乎不工作:

.onChange(of: Calendar.current.component(.minute, from: Date())) { _ in
                print("Minute has Changed")
                
                if calendarViewModel.isTimerAlreadyPublishing {
                    print("Timer continue publishing")
                } else {
                    calendarViewModel.startTimer()
                }
            }

字符串
也许有人可以说更多的方法,我如何才能实现这一目标?

elcex8rz

elcex8rz1#

您可以使用Timer来实现这一点,当当前时区的实际分钟变化时启动它,并每60秒更新一次视图:

struct ContentView: View {
    @State private var currentDate = Date()

    var body: some View {
        Text("Current minute: \(currentDate.minute)")
            .onAppear {
                startMinuteTimer()
            }
        
            .onChange(of: currentDate) {_ in
                //this is called when every real minute changes in current TimeZone
            }

    }

    private func startMinuteTimer() {
        // Get the number of seconds to the next minute
        let seconds = 60 - Calendar.current.component(.second, from: .now)
        // Set the initial timer to sync with the next minute change
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(seconds)) {
            self.currentDate = Date()
            // After the first trigger, set a timer to repeat every minute
            Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { _ in
                self.currentDate = Date()
            }
        }
    }
}

extension Date {
    var minute: Int {
        return Calendar.current.component(.minute, from: self)
    }
}

#Preview {
    ContentView()
}

字符串

u4vypkhs

u4vypkhs2#

试试这个:

struct CountdownView {

    let date: Date
    @Binding var timeRemaining: Int

    var body: some View {
    Text("\(timeRemaining)")
        .onChange(of: date) {
            timeRemaining -= 1
        }
    }
}

struct TimerView { 

    @State private var timeRemaining: Int = 3
    @Binding var timerDone: Bool

    var body: some View {
    TimelineView(
        .animation(minimumInterval: 1.0, paused: timeRemaining <= 0)) { context in
            CountdownView(date: context.date, timeRemaining: $timeRemaining)
        }
        .onChange(of: timeRemaining) {
            if timeRemaining < 1 {
                timerDone = true
            }
        }
    }
}

字符串
这是为了验证这个答案是否能帮助你。

相关问题