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

前端 未结 3 2013
情话喂你
情话喂你 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:52

    Having a variable inside a View which isn't attached to a @State variable or an @ObservedObject model doesn't seem to have very well defined documentation - but the general rule is that everything without a @State/@ObservedObject annotation is essentially throwaway - especially as TimerView is a struct and won't be preserved over re-renders.

    Timer.TimerPublisher is a class - so essentially this would boil down to either two use cases

    • If its transient (ie: resets when the view is removed from screen and reloaded) then put the timer in a @State (be aware of strong retention with self captures - again documentation is thin on how onReceive stores its connections)
    • If its non-transient (ie: preserved over the view loading/unloading) then it needs to go into an external model (or a global var) and brought in via the init call for TimerView

    That you have @State var secondsElapsed makes me think it should be transient

提交回复
热议问题