SwiftUI Layout Grids
SwiftUI Layout: Grids
Use LazyVGrid and LazyHGrid to arrange items in flexible grid layouts.
Lazy Grids
Lazy grids are used to display a large number of items in a grid layout.
Syntax:
LazyVGrid(columns: columns, spacing: 12)LazyHGrid(rows: rows, spacing: 12)
Example
import SwiftUI
struct GridDemo: View {
let columns = [GridItem(.flexible()), GridItem(.flexible())]
var body: some View {
LazyVGrid(columns: columns, spacing: 12) {
ForEach(1...6, id: \.self) { i in
Text("Item \(i)")
.frame(maxWidth: .infinity)
.padding(12)
.background(.blue.opacity(0.1))
.cornerRadius(8)
}
}.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { GridDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
In the example above, the grid is created using a LazyVGrid with two columns, each with a flexible width.
Adaptive Grid
Use adaptive columns to fit as many items per row as space allows.
Syntax:
[GridItem(.adaptive(minimum: 100))]LazyVGrid(columns: columns) { ... }
Example
import SwiftUI
struct AdaptiveGridDemo: View {
let columns = [GridItem(.adaptive(minimum: 100), spacing: 12)]
var body: some View {
LazyVGrid(columns: columns, spacing: 12) {
ForEach(1...12, id: \.self) { i in
Text("Card \(i)")
.frame(maxWidth: .infinity, minHeight: 60)
.background(.green.opacity(0.12))
.cornerRadius(8)
}
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { AdaptiveGridDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
In the example above, the grid is created using a LazyVGrid with adaptive columns, each with a minimum width of 100 points.