我试图显示一个使用 ObservableObject 倒计时时间的简单视图,但似乎我的 ObservedObject 已更新,但未将其更新的内容显示到其绑定视图。显示保持在 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()
}
}