0

I trying to show a simple View of counting down the time using ObservableObject but it seems my ObservedObject is updated but not showing its updated content to its binded view. The display stay at 60

import SwiftUI
import Combine

class myTimer: ObservableObject {

    @Published var timeRemaining = 60
    var timer: Timer?

    init() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector (countDownTime), userInfo: nil, repeats: true)
    }

    @objc func countDownTime () {
        if (timeRemaining < 60) {
            timeRemaining -= 1
        }
    }

    func resetCount () {
        timeRemaining = 60
    }
}

struct ContentView: View {

    @ObservedObject var myTimeCount: myTimer = myTimer()

    var body: some View {
        NavigationView{
            VStack {
                Text("Time remaining \(myTimeCount.timeRemaining)")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .padding()

                Button(action: resetCount) {
                    Text("Reset Counter")
                }
            }

        }

    }
    func resetCount() {
        myTimeCount.resetCount()
    }
}

enter image description here

FLMikeN
  • 1
  • 1

1 Answers1

0

You can also change your init slightly and get rid of @objc func countDownTime () at all


    init() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
            self?.timeRemaining -= 1
        }
    }