SwiftUI仅在查看ContentView时隐藏导航栏。

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

我有一个Content文件,正在隐藏导航栏,因为它占用了空间,并将元素推倒。ContentView中的一个按钮(使用导航链接)重定向到另一个视图。在这个另一个视图中,导航条仍然是隐藏的......为了简单起见,我把ContentView中的一些代码删掉。

//this is the view that looks "fine" (i.e. the navigation bar takes up no space)
struct ContentView: View {
    @State private var isPresentedSettings = false
    var body: some View {
        NavigationView {
            ZStack {
                VStack {
                    SettingsButton(isPresentedSettings: $isPresentedSettings)
                }
            }.navigationBarTitle("").navigationBarHidden(true)
        }
    }
}

//this is the button that pulls up the settings page view
struct SettingsButton: View {
    @Binding var isPresentedSettings: Bool
    var body: some View {
        NavigationLink (destination: SettingsPageView(isPresentedSettings: 
        self.$isPresentedSettings)) {
            Button(action: { self.isPresentedSettings.toggle() }, label: { Text("Button") })
        }
    }
}

//This is the view that should have a navigationbar but it doesn't
struct SettingsPageView: View {
    @Binding var isPresentedSettings: Bool
    var body: some View {
        NavigationView {
            VStack {
                Text("This is a view")
            }.navigationBarTitle("Settings", displayMode: .inline)
        }
    }
}

另外... ...可能有错别字,因为我只是从另一台电脑上复制了代码。对不起,先谢谢你!

swift swiftui navigationbar navigationview
1个回答
1
投票

首先,你不需要有这个 isPresentedSettings 呈现一个 NavigationLink.

NavigationLink(destination: SettingsPageView()) {
    Text("Button")
}

而且应该只有一个 NavigationView 视图层次结构中。

这就是你的最终代码的样子。

struct ContentView: View {
    @State private var navBarHidden = true

    var body: some View {
        NavigationView {
            ZStack {
                VStack {
                    SettingsButton(navBarHidden: $navBarHidden)
                }
            }
            .navigationBarHidden(navBarHidden)
        }
    }
}
struct SettingsButton: View {
    @Binding var navBarHidden: Bool

    var body: some View {
        NavigationLink(destination: SettingsPageView(navBarHidden: $navBarHidden)) {
            Text("Show View")
        }
    }
}
struct SettingsPageView: View {
    @Binding var navBarHidden: Bool

    var body: some View {
        VStack {
            Text("This is a view")
        }
        .navigationBarTitle("Settings", displayMode: .inline)
        .onAppear {
            self.navBarHidden = false
        }
        .onDisappear {
            self.navBarHidden = true
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.