在所有教程和官方文档中,我只在 View 加载时直接看到计时器的初始化。
@State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
及以后
.onReceive(timer) {....}
但是我应该如何仅在单击按钮时初始化计时器并将其分配给未分配/未连接的计时器。
稍后我需要取消并重新连接,但这不是这里的问题。这里的问题是仅在单击按钮后才能连接。
我尝试像这样初始化它
@State private var timer: Cancellable?
...
timer = Timer.publish(every: 1, on: .main, in: .common).connect()
但是我不能像这样在计时器初始化时调用 onReceive,因为首先:
Protocol 'Cancellable' as a type cannot conform to 'Publisher'
第二个
Argument type 'Cancellable?' does not conform to expected type 'Cancellable'
最佳答案
只需将计时器放在 subview 中并使用 bool 值控制其可见性即可。当 TimerView
被移除时,状态被破坏并且计时器停止。
struct ContentView: View {
@State var started = false
var body: some View {
VStack {
Button(started ? "Stop" : "Start") {
started.toggle()
}
if started {
TimerView()
}
}
}
}
struct TimerView: View {
@State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
...
关于swift - 单击按钮后计时器发布者初始化计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73132771/