我在视图模型类中有一个计时器,该计时器每秒钟更改视图模型中的两个@Published字符串。视图模型类是一个可观察的对象,可被视图观察,但是对这些字符串对象的更改不会更新我的视图。
我在许多其他视图中具有非常相似的结构(在ObservableObject内的已发布变量由视图观察),并且始终有效。我似乎找不到我在做什么错?
final class QWMeasurementViewModel: ObservableObject {
@Published var measurementCountDownDetails: String = ""
@Published var measurementCountDown: String = ""
private var timer: Timer?
private var scheduleTime = 0
func setTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
DispatchQueue.main.async {
self.scheduleTime += 1
if self.scheduleTime == 1 {
self.measurementCountDownDetails = "Get ready"
self.measurementCountDown = "1"
}
else if self.scheduleTime == 2 {
self.measurementCountDownDetails = "Relax your arm"
self.measurementCountDown = "2"
}
else if self.scheduleTime == 3 {
self.measurementCountDownDetails = "Breathe"
self.measurementCountDown = "3"
}
else if self.scheduleTime == 4 {
self.measurementCountDownDetails = ""
self.measurementCountDown = ""
timer.invalidate()
}
}
}
}
}
struct QWMeasurementView: View {
@ObservedObject var viewModel: QWMeasurementViewModel
var body: some View {
VStack {
Text(viewModel.measurementCountDownDetails)
.font(.body)
Text(viewModel.measurementCountDown)
.font(.title)
}
.onAppear {
viewModel.setTimer()
}
}
}
经过调查,这似乎与它的呈现方式有关。因为如果是单一视图,则此代码有效,但实际上是作为表格展示的。 (仍然无法理解为什么会有所作为。)
struct QWBPDStartButtonView: View {
@ObservedObject private var viewModel: QWBPDStartButtonViewModel
@State private var startButtonPressed: Bool = false
init(viewModel: QWBPDStartButtonViewModel) {
self.viewModel = viewModel
}
var body: some View {
Button(action: {
self.startButtonPressed = true
}) {
ZStack {
Circle()
.foregroundColor(Color("midGreen"))
Text("Start")
.font(.title)
}
}
.buttonStyle(PlainButtonStyle())
.sheet(isPresented: $startButtonPressed) {
QWMeasurementView(viewModel: QWMeasurementViewModel())
}
}
}
答案 0 :(得分:0)
您正在将全新的视图模型传递到工作表视图。 尝试从第3行传入实例