使用XCode 11.4,Swift 5.0
我希望每当我创建的变量(存储在应用程序的用户默认设置中)更改时,ContentView中的Text变量(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。非常感谢任何见识!
如果您在类中使用某个函数,例如我要更新您的变量(在本例中为校正变量),请确保您引用的是该类函数的相同实例,而不是调用该类的新实例功能!