Home > Enterprise >  SwiftUI LazyVGrid spacing not working as expected
SwiftUI LazyVGrid spacing not working as expected

Time:03-30

The following results in a grid with no vertical spacing (correct), but with 20px horizontal spacing between each item in the grid. What am I doing wrong? I don't want any spacing whatsoever in between items.

private var columnGrid: [GridItem] = Array(repeating: .init(.flexible(), spacing: 0), count: 15)

var body: some View {
    LazyVGrid(columns: columnGrid, spacing: 0) {
        ForEach(Array(viewModel.array.enumerated()), id: \.offset) { character in
            SomeView(char: character.element)
                .background(.red)
        }
    }
    .background(.green)
}

enter image description here

CodePudding user response:

It looks like your SomeView() content is not taking up all available space. Somewhere in it you could use:

.frame(maxWidth: .infinity)

Here is da demo:

    private var columnGrid: [GridItem] = Array(repeating: .init(.flexible(), spacing: 0), count: 15)

    var body: some View {
        LazyVGrid(columns: columnGrid, spacing: 0) {
            ForEach(0..<40) { character in
                Text("\(character)")
                    .frame(height: 50)
                    .frame(maxWidth: .infinity) // here
                    .border(.primary, width: 1)
                    .background(.gray)
            }
        }
        .background(.green)
        .padding()
    }

enter image description here

  • Related