Search code examples
xcodeswiftuiswiftui-list

SwiftUI: listRowInsets not working as expected


listRowInsets(_:) is not working as expected when using List() and List(Data,id). in Example 1 below works perfectly with zero insets, while in Example 2 it does nothing.


Example 1:

struct ContentView: View {
    var body: some View {
        List {
            Color.red
                .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
            Color.blue
                .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
            Color.yellow
                .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
        }
    }
}

The Result:

Example 1


Example 2

struct ContentView: View {
    var colors: [Color] = [.red, .blue, .yellow]
    var body: some View {
        List(colors, id: \.self) { color in
            color.listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
        }
    }
}

The Result:

Example 2


Solution

  • I assume the reason is in used constructors. The .listRowInsets by documentation affects view being placed in List (directly).

    The following works

    var colors: [Color] = [.red, .blue, .yellow]
    var body: some View {
        List {
            ForEach(colors, id: \.self) { color in
                color.listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
            }
        }
    }