Search code examples
swiftuicountdowntimernavigationview

SwiftUI - When the countdown is over, jump to another view


When the countdown is over, I want to jump to another view. I tried navigationLink but it didn't work.

This is my code.

struct TimerView: View {

    @State var timeRemaining = 5

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Text("\(timeRemaining)")
            .font(.largeTitle)
            .onReceive(timer) { _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1

                }
            }
    }
}

Solution

  • try some variation of this:

    struct TimerView: View {
        @State var timeRemaining = 5
        @State var jump = false
        
        let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
        
        var body: some View {
            NavigationView {
                VStack {
                    Text("\(timeRemaining)")
                        .font(.largeTitle)
                        .onReceive(timer) { _ in
                            if timeRemaining > 0 {
                                timeRemaining -= 1
                            } else {
                                jump = true
                                // optional stop the timer
                                timer.upstream.connect().cancel()
                            }
                        }
                    NavigationLink("", destination: Text("the other view"), isActive: $jump)
                }
            }
        }
    }