是否有ObservableObject错误

时间:2020-03-01 15:28:47

标签: timer observable swiftui

当计数达到3时,我仍然有问题,重置功能仅将其停止,但计数未设置为0。我将重置功能与按钮配合使用,效果很好。我想了解它,希望有人知道它的原因?

import SwiftUI
import Combine
import Foundation

class WaitingTimerClass: ObservableObject {

    @Published var waitingTimerCount: Int = 0

    var waitingTimer = Timer()

    func start() {
        self.waitingTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            self.waitingTimerCount += 1 }}

    func stop() { waitingTimer.invalidate() }

    func reset() { waitingTimerCount = 0; waitingTimer.invalidate() }

}

struct ContentView: View {

    @ObservedObject var observed = WaitingTimerClass()

    var body: some View {
        VStack {
        Text("\(self.observed.waitingTimerCount)")
            .onAppear { self.observed.start() }
                    .onReceive(observed.$waitingTimerCount) { count in
                        guard count == 3 else {return}
                        self.observed.reset()    // does not work
                    }

            Button(action: {self.observed.start()}) {
                Text("Start") }

            Button(action: {self.observed.reset()}) {     // works
                Text("Reset") }

            Button(action: {self.observed.stop()}) {
            Text("Stop") }
           }
        }
    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1 个答案:

答案 0 :(得分:1)

这是因为resetbody构造期间更改了影响UI的属性,因此被忽略。应该进行如下更改

func reset() {
    waitingTimer.invalidate()
    DispatchQueue.main.async {
        self.waitingTimerCount = 0
    }
}