Placing interactable views in front of a NavigationView's hidden navigation bar

Viewed 1883

I have a NavigationView with a NavigationButton inside of it, but I cannot get the NavigationButton to be at the top of the screen and still be able to be pressed, even though the navigation bar is hidden.

This code:

struct ContentView : View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationButton(destination: Text("Button Clicked")) {
                    Text("Hello World")
                    .background(Color.yellow)
                }
                Spacer()
            }
        }
        .navigationBarHidden(true)
    }
}

Looks like this, but I want it to look like this.

I've tried adding a negative padding to the top of the VStack (with .padding([.top], -95), and it visually works, but then I can't interact with the button by tapping it (I think it is behind the hidden navigation bar). I've tried setting the VStack's zIndex to 10000 to solve that, but it still didn't work. Is there a way for me to move the button up to the top while still making sure that the button recognizes when it is being tapped?

2 Answers

Add a navigationBarTitle before hiding your navigation bar:

struct ContentView : View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationButton(destination: Text("Button Clicked")) {
                    Text("Hello World")
                    .background(Color.yellow)
                }
                Spacer()
        }
        .navigationBarTitle(Text("Title")) // Add this line
        .navigationBarHidden(true)
    }
}

Add this modifier to your NavigationView edgesIgnoringSafeArea(.top).

Related