Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI configure LazyVGrid with no spacing

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.

like image 781
randomor Avatar asked Jul 22 '20 02:07

randomor


1 Answers

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)
            }
        }
    }
}
like image 128
Asperi Avatar answered Dec 06 '22 22:12

Asperi