Tuesday, May 12, 2026
HomeiOS Developmentios - @Publish counters not in sync inside timer SwiftUI

ios – @Publish counters not in sync inside timer SwiftUI

[ad_1]

I am engaged on an app the place I am utilizing a timer to depend down time left in a exercise and in addition depend up for whole time. My counters are out of sync, appears prefer it’s lower than a second off. I am questioning if it has one thing to do with @Publish, perhaps one fires earlier than the opposite. Any concept what’s occurring and methods to repair it?

class TimeManager: ObservableObject {

   @Printed var totalTime: Double = 0.0
   @Printed var timeRemaining: Double = 180.0

   DispatchQueue.predominant.asyncAfter(deadline: DispatchTime.now() + 2.0) {
      self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] timer in
         guard let self = self else { return }
         
         self.timeRemaining -= 0.1
         self.totalTime += 0.1
     }
   }
}

then my view

@ObservedObject var timeManager = TimeManager()
 ...

var physique: some View {
    
    VStack {
       let time = timeManager.timeRemaining
       let minutes = Int(time) / 60 % 60
       let seconds = Int(time) % 60
            
       ZStack {
          Progress()
          Textual content(String(format:"%02i:%02i", minutes, seconds))
          .font(.system(dimension: 60))
       }
            
       let whole = timeManager.totalTime
       let totalMins = Int(whole) / 60 % 60
       let totalSecs = Int(whole) % 60

       Textual content(String(format:"%02i:%02i", totalMins, totalSecs))
       .font(.system(dimension: 40))
   }
}

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments