13

I wanted to create a grid of cells with no spaces or smaller space just like the Photos app, is it possible with SwiftUI 2 LazyVGrid? I've tried it but there is always this space in-between columns.

In the documentation, the spacing parameter is described as:

spacing The spacing beween the grid and the next item in its parent view.

Which doesn't make much sense, can't you just use padding for that? Also, when I tried increasing the spacing, it seems to be actually impacting the space in-between rows of cells, which is even more unexpected.

randomor
  • 4,353
  • 3
  • 37
  • 63

1 Answers1

27

You give spacing: 0 in LazyVGrid for vertical spacing, and spacing: 0 in GridItem for horizontal spacing.

Here is a demo. Tested with Xcode 12 / iOS 14

demo

struct TestImagesInGrid: View {
    @State private var imageNames: [String]

    private let threeColumnGrid = [
        GridItem(.flexible(minimum: 40), spacing: 0),
        GridItem(.flexible(minimum: 40), spacing: 0),
        GridItem(.flexible(minimum: 40), spacing: 0),
    ]

    init() {
        _imageNames = State(initialValue: (0..<8).map { _ in
            "image_\(Int.random(in: 1...3))"
        })
    }

    var body: some View {
        LazyVGrid(columns: threeColumnGrid, alignment: .leading, spacing: 0) {
            ForEach(imageNames.indices) { i in
                Image(imageNames[i]).resizable()
                    .aspectRatio(1, contentMode: .fill)
                    .border(Color.black)
            }
        }
    }
}
Asperi
  • 123,447
  • 8
  • 131
  • 245
  • Exactly what I'm looking for! The docs was misleading on the Grid. Your wording is much more clearer. The docs for GridItem: https://developer.apple.com/documentation/swiftui/griditem – randomor Jul 23 '20 at 02:37