1

I have a set up like this:

NavigationStack {
    List {
        ForEach(allProjects) { project in
            Section {
                NavigationLink(destination: ProjectView()) {
                    ProjectRow(project: project)
                }
            }
        }
    }
}

This gives me the following result

NavigationStack SwiftUI

While this is fine, I want to add some padding between the list and the navigation bar title so add some padding to the top of the list with .padding(.top, 8) and this gives me a strange result:

NavigationStack SwiftUI issue extra padding

While it does give me additional padding, it makes the whole navigation bar white for some reason.

I also tried putting the List inside a Vstack and adding the padding to the Vstack, but it gives me the same result.

Any idea why this happens and how can I get padding to the navigation title when using a List ?

Shawn Frank
  • 4,381
  • 2
  • 19
  • 29

1 Answers1

0

You will notice that before the padding was added, the background behind the title was the same as the background of the List. My guess is that the List background uses ignoresSafeArea, which makes it extend to the top of the display if it is the first item in the NavigationStack. When padding is added, it breaks the contact with the top of the display, so the default system background then shows behind the title.

The gray ("grouped") background can be restored behind the title by applying a background to the List after the padding:

        NavigationStack {
            List {
                Text("hello")
            }
            .navigationTitle("Projects")
            .padding(.top, 10)
            .background(
                Color(UIColor.systemGroupedBackground)
            )
        }

TitlePadding

Note that background(_:ignoresSafeAreaEdges:) ignores all safe edges by default, which is why it is not necessary to add an additional modifier to achieve this.

However, there is now a new surpise: the padding is supplemented with even more extra padding, so that top padding of 10 actually turns into top padding of about 45. This seems to depend on the listStyle in use. I am guessing that certain styles have hidden sections which cause more spacing to be seen once padding is applied.

The best fix I could find for the excess padding is based on this answer to the question Remove top padding from List in SwiftUI, like this:

        NavigationStack {
            List {
                Section(header: Spacer(minLength: 0)) {} // ADDED
                Text("hello")
            }
            .navigationTitle("Projects")
//            .padding(.top, 10)
            .padding(.top, -53) // = -63 + 10
            .background(
                Color(UIColor.systemGroupedBackground)
            )
        }

ExcessPaddingFixed

Benzy Neez
  • 1,546
  • 2
  • 3
  • 10