SwiftUI加倍嵌套的NavigationLink视图不响应更改的ObservedObject

时间:2020-02-26 20:54:14

标签: swiftui-navigationlink swiftui

我已经创建了三个视图。我按顺序将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的问题吗,而该代码或API不能在以这种方式显示视图的双嵌套调用中起作用?

编辑:使用XCode 11.3和iOS 13.3.1

1 个答案:

答案 0 :(得分:0)

我想这是一个提供所需行为的布局

var body: some View {
    Group {
        if !userDefaultsManager.setupComplete {
            NavigationView {
                VStack {
                    Button(action: {
                        self.showAnotherView.toggle()
                    }) {
                        Text("Show Another View")
                    }
                    NavigationLink(destination: AnotherView(userDefaultsManager: userDefaultsManager), isActive: $showAnotherView, label: {
                        EmptyView()
                    })
                }
            }
        } else {
            Text("YES IT IS FINISHED!")
        }
    }
}