ios 如何在计时器结束时切换视图SwiftUI

ar7v8xwq  于 2022-11-19  发布在  iOS
关注(0)|答案(1)|浏览(160)

我有两个视图。主视图和中断视图。我有一个计时器在主视图中运行,它会倒计时到零。当计时器达到零时,我希望能够将屏幕切换到中断视图。我使用MVVM跟踪计时器。使用.onReceive使计时器看起来像是在后台运行。
我试着用布尔值来检查计时器是否已经达到零,并基于此更改视图,但它不起作用,并给出一个错误,说视图的结果没有在任何地方使用。如果有任何帮助,我在内容视图中有一个导航视图。
先谢谢你。
代码片段:
主视图:

struct MainView: View {

    var body: some View {
       
                VStack(alignment: .center, spacing: 50, content: {

                        Button(action: {
                            if !fbManager.isTimerStarted {
                                fbManager.start()
                                fbManager.isTimerStarted = true
                            }
                            else {
                                 fbManager.pause()
                                 fbManager.isTimerStarted = false
                            }
                            
                        }, label: {
                            Image(systemName: fbManager.isTimerStarted == true ? "pause.fill" : "play.fill")
                                .resizable()
                                .scaledToFit()
                                .frame(width: 50, height: 50)
                                .foregroundColor(Color(red: 1.00, green: 1.00, blue: 1.00))
                        })
                        .onReceive(NotificationCenter.default.publisher(
                            for: UIScene.didEnterBackgroundNotification)) { _ in
                                if fbManager.isTimerStarted {
                                    movingToBackground()
                                }
                                
                        }
                            .onReceive(NotificationCenter.default.publisher(
                                for: UIScene.willEnterForegroundNotification)) { _ in
                                    
                                    if fbManager.isTimerStarted {
                                        movingToForeground()
                                    }
                                    
                                }
                })
        }
    }
    
    func movingToBackground() {
        print("Moving to the background")
        notificationDate = Date()
        fbManager.pause()
    }
    
    func movingToForeground() {
        
        print("Moving to the foreground")
        
        let deltaTime: Int = Int(Date().timeIntervalSince(notificationDate))
        fbManager.secondsElapsed -= deltaTime
        fbManager.start()
    }
    
}

查看型号:

class FocusBreakManager: ObservableObject {
  
    var timer: Timer = Timer()

    func start() {
        
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [self] _ in
            
            self.secondsElapsed -= 1
            self.focusfill += 0.01667
            focusTime = String(secondsElapsed)
            focusTime = formatCounter()
            
            if secondsElapsed <= 0 {
                
                stop()

            }

        }
    }
 
    func formatCounter() -> String {
        
        let minutes = Int(secondsElapsed) / 60 % 60
        let seconds = Int(secondsElapsed) % 60
        return String(format : "%02i : %02i", minutes, seconds)
    }
    
}
68bkxrlz

68bkxrlz1#

嘿,为了跟上你的解决方案,这里有一个如何工作的例子,你需要使用@ObservedObject属性 Package 器,以便从你的视图监视更新。

struct ContentView: View {

    @ObservedObject private var focusBreakManager = FocusBreakManager()

    var body: some View {
        VStack {
            Text("\(focusBreakManager.elapsedSeconds)")
            Text(focusBreakManager.timerRunningMessage)
            Button("Start timer", action: focusBreakManager.start)
        }
        .padding()
    }
}

class FocusBreakManager: ObservableObject {

    var timer: Timer = Timer()
    @Published var elapsedSeconds = 0

    var timerRunningMessage: String {
        timerRunning
        ? "Timer is running"
        : "Timer paused"
    }

    private var timerRunning: Bool {
        timer.isValid
    }

    func start() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
            guard let self else { return }
            self.elapsedSeconds += 1
            if self.elapsedSeconds > 5 {
                self.timer.invalidate()
            }
        }
    }

}

你也可以看看autoconnect api这里有一个很棒的教程:https://www.hackingwithswift.com/books/ios-swiftui/triggering-events-repeatedly-using-a-timer

相关问题