问题描述
我在 SwiftUI 中通过 UserDefaults (App Storage) 保存整数,但现在的问题是,在不同的结构中,整数仅在重新启动应用程序后加载,但当您单击导航链接时,应立即加载整数视图来了。整数(通过 if 查询以文本形式)立即加载到相同的结构中。
如果有人能帮助我,我很高兴。
先谢谢你:)
演示代码:
import SwiftUI
struct Monday1BCalendarView: View {
@AppStorage("Monday1B") var Monday1B: Int = 1
var body: some View {
Form{
Section(header: Text("Main")){
Button(action: {
self.Montag1B = 0;
},label: {
Text("Maths")
.foregroundColor(.primary)
})
和加载:
import SwiftUI
struct CalendarMainView: View {
var Monday1B: Int = UserDefaults.standard.integer(forKey: "Monday1B")
var body: some View {
NavigationView {
vstack{
ZStack{
Image("Stundenplan")
.resizable()
.frame(width: 360,height: 200,alignment: .center)
.position(x: 200,y: 100)
if Montag1B == 0 {
Text("Mathe")
}
解决方法
此行仅在初始化时从 UserDefaults
读取:
struct CalendarMainView: View {
var Monday1B: Int = UserDefaults.standard.integer(forKey: "Monday1B")
如果你想观察这个值的变化,你需要@AppStorage
:
struct CalendarMainView: View {
@AppStorage("Monday1B") var Monday1B: Int = 1
...
如果您最终拥有多个 @AppStorage
包装器,您可以在父视图中创建一个并将其传递给子视图。
您必须在两个(所有)地方都使用 @AppStorage
struct CalendarMainView: View {
// this automatically updated
@AppStorage("Montag1B") var Montag1B: Int = 0
// this read only once - on initialization
//var Montag1B = UserDefaults.standard.integer(forKey: "Montag1B")