我创建了三个视图。我按顺序将 ObservedObject 状态传递给每个视图。当我更改最后一个视图 (AnotherView2) 中的状态时,我的应用程序没有显示“是的,它已完成!”的文本视图。但是,如果我在 AnotherView 中取消注释此行
self.userDefaultsManager.setupComplete = true
它通过显示文本按我预期的方式工作。
struct ContentView: View {
@ObservedObject var userDefaultsManager = UserDefaultsManager()
@State var showAnotherView: Bool = false
var body: some View {
NavigationView {
VStack {
if !userDefaultsManager.setupComplete {
Button(action: {
self.showAnotherView.toggle()
}) {
Text("Show Another View")
}
NavigationLink(destination: AnotherView(userDefaultsManager: userDefaultsManager), isActive: $showAnotherView, label: {
EmptyView()
})
} else {
Text("YES IT IS FINISHED!")
}
}
}
}
}
struct AnotherView: View {
@ObservedObject var userDefaultsManager: UserDefaultsManager
@State var showAnotherView2: Bool = false
var body: some View {
VStack {
Button(action: {
//self.userDefaultsManager.setupComplete = true
self.showAnotherView2 = true
}, label: {
Text("Press")
})
NavigationLink(destination: AnotherView2(userDefaultsManager: userDefaultsManager), isActive: $showAnotherView2, label: {
EmptyView()
})
}
}
}
struct AnotherView2: View {
@ObservedObject var userDefaultsManager: UserDefaultsManager
var body: some View {
Button(action: {
self.userDefaultsManager.setupComplete = true
}, label: {
Text("Just Do It")
})
}
}
class UserDefaultsManager: ObservableObject {
@Published var setupComplete: Bool = UserDefaults.standard.bool(forKey: "setupComplete") {
didSet { UserDefaults.standard.set(self.setupComplete, forKey: "setupComplete") }
}
}
有人可以帮助我了解我的代码或 API 有什么问题,它不能用于以这种方式显示视图的双嵌套调用吗?
编辑:使用 XCode 11.3 & iOS 13.3.1