Home > other >  SwiftUI Remove Spacing from Top Of List in NavigationView
SwiftUI Remove Spacing from Top Of List in NavigationView

Time:07-30

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.

CodePudding user response:

Just remove section's title

    NavigationView {
        List {
            Section {     // << here !!
                ForEach((1...10), id: \.self) {
                    Text("\($0)")
                }
            }
        }
        .border(.red)   // << for test
        .navigationTitle("Title")
    }

Tested with Xcode 13.4 / iOS 15.5.

demoenter image description here

Added variant with header title - just remove default header's insets

    List {
        Section {
            ForEach((1...10), id: \.self) {
                Text("\($0)")
            }
        } header: {
            Text("Title")
                .listRowInsets(EdgeInsets())  // << here !!
        }
    }

CodePudding user response:

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)
    }
}
  • Related