swiftswiftuiswiftui-listswiftui-navigationview

SwiftUI Remove Spacing from Top Of List in NavigationView


I have a simple SwiftUI view that uses Section's within a List:

struct NewView: View {
    var body: some View {
        NavigationView {
            List {
                Section("Title") {
                    ForEach((1...10), id: \.self) {
                        Text("\($0)")
                    }
                }
            }
            .navigationTitle("Title")
        }
    }
}

When ran (in iOS 15) this leaves a massive gap at the top (compared to when there is no section title):

With Section Without Section

How do I reduce this spacing?

I have tried hacky solutions like:

UITableView.appearance().contentInset.top = -35

but that makes scrolling the scroll view buggy and I hope there is a better way.


Solution

  • The cobination of .environment(\.defaultMinListHeaderHeight, 1) and .listRowInsets worked for me:

    var body: some View {
        NavigationView {
            List {
                Section("Title") {
                    ForEach((1...10), id: \.self) {
                        Text("\($0)")
                    }
                }
                .listRowInsets(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
            }
            .navigationTitle("Title")
            .environment(\.defaultMinListHeaderHeight, 1)
        }
    }