0

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

soleil
  • 12,133
  • 33
  • 112
  • 183
  • Could you show the output you currently have? Before that, if you add `.background` modifiers with distinctive colors to `LazyVGrid` and `SomeView`, it will help to find out where exactly the unwanted spacing appears. – lazarevzubov Mar 29 '22 at 05:01
  • It's expected behavior in case when if your `SomeView` doesn't have enough width, for example try adding `.frame(maxWidth: .infinity)` – Phil Dukhov Mar 29 '22 at 05:07
  • 1
    @lazarevzubov I updated the question with the background modifiers and an image. – soleil Mar 29 '22 at 05:08
  • @PylypDukhov thanks for the suggestion. It didn't solve the problem though. – soleil Mar 29 '22 at 05:09
  • 1
    Have you added it to `SomeView`? It should be added before `background(.red)`. If this still doesn't help, please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Phil Dukhov Mar 29 '22 at 05:11

1 Answers1

2

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

Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
ChrisR
  • 9,523
  • 1
  • 8
  • 26