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
Demo.swift
ContentView.swift
App.swift
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()
}
}
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
Demo.swift
ContentView.swift
App.swift
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()
}
}
Leave a Reply