【发布时间】:2020-07-15 02:21:38
【问题描述】:
使用 XCode 11.4、Swift 5.0
每当我创建的变量(存储在应用程序的用户默认值中)发生更改时,我希望更新 ContentView 中的文本变量 (correctionLabel)。下面的代码显示了我尝试在输入变量更改时使用didSet 更新 ContentView 中的文本:
//ContentView.swift
//this is a single page application
import SwiftUI
let defaults = UserDefaults.standard
var correctionLabel = Text("O")
var corrections = defaults.integer(forKey: "CorrectionCount") {
didSet {
correctionLabel = Text("\(corrections)")
print("old value is \(oldValue) and new value is \(corrections)")
print(correctionLabel)
}
}
struct ContentView: View {
var body: some View {
correctionLabel
}
}
//code for incrementing the corrections variable not shown here
该应用程序的其他所有内容都经过测试并且可以正常工作,使用print() 测试进行验证,以确保在更改 iPhone 方向时corrections 变量确实在增加。
但是,屏幕上的计数器从 0 开始但从不增加,并且控制台显示 print(correctionLabel) 的此错误:
Text(storage: SwiftUI.Text.Storage.anyTextStorage(SwiftUI.(unknown context at $1cf871518).LocalizedTextStorage), modifiers: [])
我觉得问题一定是小问题,我在这里遗漏了一些东西,因为所需的最终产品是一个简单的屏幕计数器,它从 0 开始并以 1 递增。非常感谢任何见解!
【问题讨论】:
标签: properties textview swift5 xcode11 observers