0
0
iOS Swiftmobile~5 mins

Grid layout (LazyVGrid, LazyHGrid) in iOS Swift

Choose your learning style9 modes available
Introduction

Grid layouts help you show many items in rows and columns. They make your app look neat and organized.

Showing a photo gallery with many pictures.
Displaying a list of products in a shopping app.
Creating a calendar view with days in a grid.
Arranging buttons or icons evenly on the screen.
Syntax
iOS Swift
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {
    // Your views here
}

LazyHGrid(rows: [GridItem(.fixed(50)), GridItem(.fixed(50))]) {
    // Your views here
}

LazyVGrid arranges items vertically in columns.

LazyHGrid arranges items horizontally in rows.

Examples
This creates a vertical grid with 2 columns. Items fill rows from left to right.
iOS Swift
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
    Text("Item 4")
}
This creates a horizontal grid with 2 rows. Items fill columns from top to bottom.
iOS Swift
LazyHGrid(rows: [GridItem(.fixed(50)), GridItem(.fixed(50))]) {
    Text("A")
    Text("B")
    Text("C")
    Text("D")
}
Sample App

This app shows 9 items in a vertical grid with 3 columns. Each item is a blue box with white text. The grid scrolls if needed.

iOS Swift
import SwiftUI

struct ContentView: View {
    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(1...9, id: \.self) { number in
                    Text("Item \(number)")
                        .frame(height: 50)
                        .frame(maxWidth: .infinity)
                        .background(Color.blue.opacity(0.7))
                        .foregroundColor(.white)
                        .cornerRadius(8)
                }
            }
            .padding()
        }
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
OutputSuccess
Important Notes

Use GridItem(.flexible()) to make columns or rows share space equally.

Use GridItem(.fixed(value)) to set exact size for columns or rows.

Lazy grids only create views when needed, so they help performance with many items.

Summary

LazyVGrid arranges items vertically in columns.

LazyHGrid arranges items horizontally in rows.

Use GridItem to control size and spacing of grid cells.