导航到其他页面后,如何在SwiftUI中恢复已发布的计时器? [英] How do I resume a published timer in SwiftUI after navigating to a different page?
问题描述
在下面的Playground示例中,UI会正确地使用当前日期进行更新,但是,当离开页面导航并返回时,计时器不会继续计时:
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:
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())
当页面开始显示时,如何使计时器重新开始更新?
How do I have the timer start updating again when the page starts showing?
我看到了一些解决方案,其中涉及将Timer包装到另一个类中,但是在View中无法执行任何操作.
I have seen solutions that involve wrapping the Timer in another class, but nothing that can be done in the View.
我认为在 onAppear {}
中的 connect()
中进行调用会做到这一点.
I thought calling in connect()
in onAppear {}
would do it.
推荐答案
在onAppear内重新初始化计时器和日期将可行:
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")
}
}
}
}
这篇关于导航到其他页面后,如何在SwiftUI中恢复已发布的计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!