0

我试图显示一个使用 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()
    }
}

在此处输入图像描述

4

1 回答 1

0

@objc func countDownTime ()您也可以稍微更改您的 init 并完全摆脱


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

于 2020-05-30T19:26:04.133 回答