ioslistswiftuialignmentios18

How to Align Section Header with List Items in SwiftUI on iOS 18.2?


I am trying to align the section header with the start of the list item rows in SwiftUI (tested on iOS 18.2). However, the header does not align properly with the list items.

Here is my code:

    List {
        Section {
            Text("Row")
            Text("Row")
            Text("Row")
        } header: {
            Text("Header")
        }
        .headerProminence(.increased)
    }

I also tried wrapping the header in a VStack to set an alignment explicitly:

    List {
        Section {
            Text("Row")
            Text("Row")
            Text("Row")
        } header: {
            VStack(alignment: .leading) {
                Text("Header")
            }
        }
        .headerProminence(.increased)
    }

Despite these attempts, the header is still not aligning with the rows.

Here's image of the issue.

Does anyone have suggestions or workarounds to fix this alignment issue?


Solution

  • Thanks to workingdog's suggestion, I tried using listRowInsets on the header text, which allowed me to adjust the vertical alignment of the header to match the rows. I also experimented with alignmentGuide, but I couldn't get it to work—perhaps I implemented it incorrectly.

    The solution that worked for me was using listRowInsets to align the header with the left side of the rows. I adjusted the top and bottom edge insets by trial and error until the alignment looked the same as before. Here’s the code I used:

    List {
        Section {
            Text("Row")
            Text("Row")
            Text("Row")
        } header: {
            Text("Header")
                // This is the fix
                .listRowInsets(EdgeInsets(top: 8, leading: 0, bottom: 11, trailing: 0)) 
        }
        .headerProminence(.increased)
    }
    

    Image of before and after.

    This approach resolved the issue for me, and I hope it helps others facing the same problem.