How it works
A GridItem describes a single row or column in a grid, telling SwiftUI how much space that track may occupy and how much spacing separates it from its neighbor. You supply an array of these values to a LazyVGrid or LazyHGrid, and the grid repeats your content across them to form its layout axis. Reach for GridItem whenever you need precise control over a grid's column or row sizing rather than letting the grid guess. Each value is lightweight and declarative, so you describe the track shape once and the grid lays out an arbitrary number of items into it.
Choose a sizing behavior with GridItem.Size
The first argument to
GridItem(_:)is aGridItem.Sizethat picks how the track measures itself:.fixedfor a constant width,.adaptiveto pack as many items as fit, or.flexibleto share remaining space evenly. The example passes.flexible(), so each of the three tracks expands to take an equal portion of the grid's width.Separate tracks with the spacing parameter
The
spacingparameter sets the gap between this track and the next one along the layout axis, independent of the spacing the grid itself applies between rows. Here everyGridItem(.flexible(), spacing: 8)reserves 8 points between its column and the following column.Define the layout by collecting GridItems into an array
A grid's shape is the array of
GridItemvalues you hand it; its length determines the number of columns (forLazyVGrid) or rows (forLazyHGrid). Thecolumnsarray holds threeGridItementries, so the grid lays content out in three columns and wraps to a new row after every third item.Hand the array to the grid's columns argument
LazyVGridtakes that array through itscolumns:parameter and flows its child views across the described tracks. In the example,LazyVGrid(columns: columns, spacing: 8)consumes the threeGridItemvalues and arranges its content into them, applying its ownspacing: 8between the resulting rows.
columns array from three GridItem(.flexible(), spacing: 8) entries to a single GridItem(.adaptive(minimum: 80)) and watch the grid pack as many columns as the width allows instead of a fixed three.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct GridItemDemo: View {
let columns = [
GridItem(.flexible(), spacing: 8),
GridItem(.flexible(), spacing: 8),
GridItem(.flexible(), spacing: 8)
]
var body: some View {
LazyVGrid(columns: columns, spacing: 8) {
ForEach(1...9, id: \.self) { i in
Text("\(i)")
.frame(maxWidth: .infinity, minHeight: 50)
.background(Color.blue.opacity(0.2))
.cornerRadius(8)
}
}
.padding()
}
}