How can I remove the minimum vertical padding or minimum height of a List row in SwiftUI?

Viewed 225

I am trying to add a very short row to my list with a frame height of 2 but the list is adding an undesired padding above and below the list item or constraining to a minimum height and I don't know how to remove it. I have produced the following to illustrate the problem:

struct ContentView: View {
    var body: some View {
        List {
            Color.red
                .frame(height: 2)
            Color.blue
                .frame(height: 2)
        }
    }
}

enter image description here

How can I remove this padding above and below the list item? It's the same if using a section and adding header or footer. It will not allow me to have a list entry with small frame height.

In a LazyVStack I don't have this problem but I need to use a list.

1 Answers
  1. Use .environment(\.defaultMinListRowHeight, 0) to make each row have a minimum height of 0. Otherwise, each row will always be at least 44 (the default) points high.
  2. Use .listRowInsets(EdgeInsets()) to make each row have no inset. You could also do .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)), which results in the same.
struct ContentView: View {
    var body: some View {
        List {
            Color.red
                .frame(height: 5)
                .listRowInsets(EdgeInsets()) /// 2.
            Color.blue
                .frame(height: 5)
                .listRowInsets(EdgeInsets())
        }
        .environment(\.defaultMinListRowHeight, 0) /// 1.
    }
}

Result:

Blue and red lines stacked vertically, with no gap in between
Related