Search code examples
listviewswiftuiswiftui-navigationlink

SwiftUI - destination of NavigationLink creates view with extra space


I've whittled my login page down to a single NavigationLink that leads to a List view as its destination. The problem, as you can see in the image below, is that instead of the nicely spaced title on the left, I get the huge space as shown on the right. Both views are the same, but the one on the right is the preview of the page as it was designed. The image on the left is the preview of the page after coming from the login screen.

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            NavigationLink(destination: CustomerView()) {
                Text("login")
            }
        }
    }
}

enter image description here

Here is the code for the List view:

var body: some View {
        
        NavigationView {
            VStack {
                SearchBarView(text: $searchText)
                    .padding(.top, 0)
                List {
                    ForEach(customers.filter({searchText.isEmpty ? true : $0.name.localizedCaseInsensitiveContains(searchText)})) { customer in
                        NavigationLink(destination: CustomerDetailView(customer: customer)) {
                            CustomerRow(customer: customer)
                        }
                        .navigationBarTitle("Customers")
                    }
                }
            }
        }
        .navigationBarBackButtonHidden(true)
    }
}

Solution

  • You don't need NavigationView twice. NavigationView should wrap top level view once and it will have over all views that you navigated. Remove NavigationView over VStack

     VStack {
        List {
            ForEach(0..<10) { index in
                NavigationLink(destination: Text("Hello \(index)")) {
                    Text("\(index)")
                }
            }
        }
    }
    .navigationBarTitle("Customers")
    .navigationBarBackButtonHidden(true)