首页 > 解决方案 > 导航到其他页面后,如何在 SwiftUI 中恢复已发布的计时器?

问题描述

在下面的 Playground 示例中,UI 会正确更新当前日期,但是当导航离开页面并返回时,计时器不会继续计时:

  import SwiftUI
  import PlaygroundSupport

  struct MainTabView: View {
    let 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 { _ = self.timer.connect() }
            .tabItem {
                Text("Page 1")
            }

            Text("Page 2").tabItem {
                Text("Page 2")
            }

            Text("Page 3").tabItem {
                Text("Page 3")
            }
        }
    }
}

PlaygroundPage.current.setLiveView(MainTabView())

当页面开始显示时,如何让计时器再次开始更新?

我已经看到涉及将 Timer 包装在另一个类中的解决方案,但在 View 中什么也做不了。

我以为打进来connect()onAppear {}行了。

标签: swifttimerswiftuicombinepublisher

解决方案


在 onAppear 中重新初始化计时器和日期会起作用:

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

推荐阅读