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

问题描述 投票:0回答:1

我创建了三个视图。我按顺序将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的问题,而该问题不适用于以这种方式显示视图的双重嵌套调用吗?

swiftui swiftui-navigationlink swiftui-bug
1个回答
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!")
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.