Contents

init(alignment:horizontalSpacing:verticalSpacing:content:)

Creates a grid with the specified spacing, alignment, and child views.

Declaration

init(alignment: Alignment = .center, horizontalSpacing: CGFloat? = nil, verticalSpacing: CGFloat? = nil, @ViewBuilder content: () -> Content)

Parameters

  • alignment:

    The guide for aligning the child views within the space allocated for a given cell. The default is Center.

  • horizontalSpacing:

    The horizontal distance between each cell, given in points. The value is nil by default, which results in a default distance between cells that’s appropriate for the platform.

  • verticalSpacing:

    The vertical distance between each cell, given in points. The value is nil by default, which results in a default distance between cells that’s appropriate for the platform.

  • content:

    A closure that creates the grid’s rows.

Discussion

Use this initializer to create a Grid. Provide a content closure that defines the rows of the grid, and optionally customize the spacing between cells and the alignment of content within each cell. The following example customizes the spacing between cells:

Grid(horizontalSpacing: 30, verticalSpacing: 30) {
    ForEach(0..<5) { row in
        GridRow {
            ForEach(0..<5) { column in
                Text("(\(column), \(row))")
            }
        }
    }
}

You can list rows and the cells within rows directly, or you can use a ForEach structure to generate either, as the example above does:

[Image]

By default, the grid’s alignment value applies to all of the cells in the grid. However, you can also change the alignment for particular cells or groups of cells: