swift - 为什么我的 ObservedObject 已更新但未在视图中显示其更新的内容
问题描述
我试图显示一个使用 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()
}
}
解决方案
@objc func countDownTime ()
您也可以稍微更改您的 init 并完全摆脱
init() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
self?.timeRemaining -= 1
}
}
推荐阅读
- sql-server - 无法使用 Citrix 主页的 Visual Studio 建立 SSIS 连接管理器,但能够使用运行选项执行 SSRS 报告
- flutter - Flutter_dotenv 的 FileNotFoundError
- django - “添加另一个”时具有不同字段集的 Django Admin Inlines
- c# - 我如何在 UWP 应用程序中实现 Twain 以扫描文档
- c - 如何在kafka中使用来自主题的特定分区的消息
- python - 我试图在 pygame 上解决这个不流畅和波涛汹涌的动画和动作,我一直在尝试一切,但没有任何效果
- json - 当我 JsonConvert.DeserializeObject 它只是停止在 asp.net 核心中工作
- mysql - 从支付工资表中获取最近 3 个月的记录,其中月份和年份存储在单独的列中
- python - openpyxl.chart 指定多个数据标题
- c# - 升级到 MSTest 2.2.4 后,自动化 selenium 测试停止工作