SwiftUI onAppear仅使用@Binding每隔第二次更改@State

时间:2020-04-06 16:01:47

标签: swift navigation swiftui

我有以下代码:

struct ContentView: View {

    @State public var navBarHidden = true

    var body: some View {

        NavigationView{
            VStack{
                ZStack(alignment: .center){
                    View1().onAppear{self.navBarHidden = true}
                    View2()
                    View3(navBarHidden: $navBarHidden)
                }.navigationBarTitle("").navigationBarHidden(self.navBarHidden)
            }
        }
    }
}


//View3
struct View3: View {

    @Binding public var navBarHidden: Bool

    var body: some View {

        NavigationView{
            VStack{
                MenuButton(buttonText: "Settings", buttonCallView: AnyView(SettingsView() .navigationBarTitle(Text("Settings"), displayMode: .inline)))
                        .simultaneousGesture(TapGesture().onEnded {
                           self.navBarHidden = false
                        })
            }
        }
    }
}

//Menu Button
struct MenuButton: View {

    var buttonText: String
    var buttonCallView: AnyView

    var body: some View {
        NavigationLink(destination: self.buttonCallView) {
            Text(self.buttonText)
            }.padding()

    }
}

当我单击此MenuButton时,导航栏会出现很好,但返回时,.onAppear中的View1应该触发,只会每隔第二次更改@State我从菜单按钮调用的子菜单中回来。我在print("one")中尝试过.onAppear,并且每次都会显示。我希望它是.onAppear的一些“晚期”响应。

我确实有解决方法。通过在视图上添加.onDisappear,按钮将调用该按钮。但这并不理想。

MenuButton(buttonText: "Settings", buttonCallView: AnyView(Settings().onDisappear{self.navBarHidden = true}.navigationBarTitle(Text("Settings"), displayMode: .inline)))
                        .simultaneousGesture(TapGesture().onEnded {
                            self.navBarHidden = false
                        })

0 个答案:

没有答案