【问题标题】:SwiftUI - When the countdown is over, jump to another viewSwiftUI - 倒计时结束后,跳转到另一个视图
【发布时间】:2023-04-09 21:18:01
【问题描述】:

倒计时结束后,我想跳转到另一个视图。 我试过navigationLink,但没有用。

这是我的代码。

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

                }
            }
    }
}

【问题讨论】:

    标签: swiftui countdowntimer navigationview


    【解决方案1】:

    尝试一些变体:

    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)
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2021-12-15
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多