'Remove extra padding above section header?
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.
The spacing goes away if I remove the section header (leaving the rows in the ForEach only).
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 1:[1]
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
}
}
...
}
Solution 2:[2]
for iOS 15 and old
if #available(iOS 15.0, *) {
yourTableView.sectionHeaderTopPadding = 0
} else {
UITableView.appearance().sectionHeaderTopPadding = CGFloat(0)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Fabio |




