[SOLVED] Remove extra padding above section header?

Issue

I have a List with fixed heights. I removed all the insets using listRowInsets.

However, a 22 point padding still remains above the section header (shrinking to zero as scrolling starts). Is there a way to remove the extra padding above the section header?

UPDATE: The extra padding only appears in iOS 15 runtimes.

enter image description here

enter image description here

The spacing goes away if I remove the section header (leaving the rows in the ForEach only).

enter image description here

import SwiftUI
import Introspect

struct ContentView: View {
        
    var body: some View {
        ZStack {
            Grid().opacity(0.1)
            VStack {
                Spacer(minLength: 60)
                List {
                    Section(
                        header: HStack {
                            Text("Section Heaeder").font(.system(size: 40))
                            Spacer()
                        }
                            .frame(height: 60)
                            .background(Grid().opacity(0.4))
                            .listRowInsets(.zero),
                        content: {
                            ForEach(1...20, id: \.self) { eachRowIndex in
                                Text("Row \(eachRowIndex)")
                                    .frame(height: 40)
                                    .listRowInsets(.zero)
                                    .listRowBackground(
                                        Rectangle()
                                            .strokeBorder(Color.white.opacity(0.2), lineWidth: 1)
                                    )
                            }
                        }
                    )
                }
                .listStyle(.plain)
                .introspectTableView {
                    $0.separatorStyle = .none
                }
                .background(Grid().opacity(0.1))
                .padding(.leading, 20)
                .padding(.trailing, 25)
                .environment(\.defaultMinListRowHeight, 40)
            }
        }
        .edgesIgnoringSafeArea(.all)
    }
}

extension EdgeInsets {
    
    static var zero = EdgeInsets()
}

struct Grid: View {
    
    var body: some View {
        Rectangle()
            .fill(
                ImagePaint(image: Image("Square"))
            )
    }
}

Solution

Use sectionHeaderTopPadding. It targets this specific spacing.

The API is only available from iOS 15, but the extra spacing itself is present in iOS 15 runtimes only.

struct ContentView: View {
        
    init() {
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0
        }
    }

    ...
}

enter image description here

Answered By – Geri Borbás

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.