SwiftUI: How do you restart a timer after cancelling it?

前端 未结 3 2029
情话喂你
情话喂你 2021-02-15 17:01

I have a navigation view consisting of the main ContentView and a TimerView. The TimerView has a timer which correctly increments and also corr

3条回答
  •  情话喂你
    2021-02-15 17:54

    if you have a countdown timer, you define it something like this:

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    

    ...and use it on a Text field for e.g.:

        Text("Punkte: \(Punkte.formatnumber())")
            .onReceive(timer) { input in
                                if time < 1 { gameOver() } else { self.time -= TimerToggle ? 1 : 0  }
                        }
    

    so you only have to set the Toggle in the action of the button:

    Button(action: { TimerToggle.toggle() }, label: {
                        Text("Pause")
                    })
    

    Much simpler and works in SwiftUI 5.2

提交回复
热议问题