【问题标题】:why my ObservedObject is updated but not showing its updated content in the View为什么我的 ObservedObject 已更新但未在视图中显示其更新的内容
【发布时间】:2020-05-30 18:59:18
【问题描述】:

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

enter image description here

【问题讨论】:

  • 已解决。我的错误检查 if 语句的错

标签: swift timer observableobject observedobject


【解决方案1】:

你也可以稍微改变你的初始化并完全摆脱@objc func countDownTime ()


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

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2020-10-22
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    相关资源
    最近更新 更多