swift - 导航到其他页面后,如何在 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 {}
行了。
解决方案
在 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")
}
}
}
}
推荐阅读
- activemq - ActiveMQ:通过 JMX 创建的网络连接器不是持久的
- api - 带有 Grails 2.5.6 的 API REST:如何在没有 UrlMapping 的情况下配置 URI?作为方法的符号?
- javascript - 根据浏览器宽度更改 JS 值
- html - css grid-template-rows 不能按预期工作(大小不随 fr 改变)
- aem - AEM 自适应表单重复电子邮件验证
- python - 在python中使用pandas从两个不同列的函数中返回2个值
- bash - 希望按数字前的最后一个字母对服务器列表进行排序
- flutter - 颤动动态设置选定按钮的颜色
- android - Android HILT SingletonComponent vs GoF Singleton 实例设计模式
- python - 如何修补 com_google_protobuf/python/google/__init__.py?