How do I resume a published timer in SwiftUI after navigating to a different page?

前端 未结 2 825
南笙
南笙 2021-01-26 10:58

In the following Playground example, the UI updates with the current date correctly, however when navigating away from the page and coming back the timer does not resume ticking

2条回答
  •  -上瘾入骨i
    2021-01-26 11:36

    Reinitializing your timer and date inside the onAppear would work:

    struct ContentView: View {
        @State private var timer = Timer.publish(every: 1, on: .main, in: .common)
        @State var time = Date()
    
        var body: some View {
            TabView {
                VStack {
                    Text("\(time)").onReceive(self.timer) { self.time = $0 }
                }
                .onAppear(perform: {
                    self.time = Date()
                    self.timer = Timer.publish(every: 1, on: .main, in: .common)
                    _ = self.timer.connect()
                })
                .tabItem {
                    Text("Page 1")
                }
    
                Text("Page 2").tabItem {
                    Text("Page 2")
                }
    
                Text("Page 3").tabItem {
                    Text("Page 3")
                }
            }
        }
    }
    

提交回复
热议问题