68

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.

2 Answers 2

138

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)
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I'm looking for! The docs was misleading on the Grid. Your wording is much more clearer. The docs for GridItem: developer.apple.com/documentation/swiftui/griditem
10

Short answer:

GridItem(.flexible(), spacing: 0),

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.