DEV Community

Cover image for LazyHGrid Grid Layout in iOS 18 - #30DaysOfSwift
Vaibhav Dwivedi
Vaibhav Dwivedi

Posted on

LazyHGrid Grid Layout in iOS 18 - #30DaysOfSwift

Day 22: Exploring LazyHGrid

Cheers to the Day 22nd of the #30DaysOfSwift series!

Today, we’re diving into SwiftUI's LazyHGrid, an efficient way to display grid-like content in a horizontal scroll view.

Whether you’re building an image gallery, a product list, or a grid-based menu, LazyHGrid helps keep your UI smooth and responsive.

Image description

We’ll create a layout with 3 rows and display a series of numbered grid items.

Code Example

import SwiftUI

struct LazyHGridExample: View {
    // Define the grid layout with 3 rows and flexible spacing
    let rows = [GridItem(.fixed(100)), GridItem(.fixed(100)), GridItem(.fixed(100))]

    var body: some View {
        ScrollView(.horizontal) { // Enable horizontal scrolling
            LazyHGrid(rows: rows, spacing: 20) { // Create LazyHGrid with 3 rows
                ForEach(0..<30) { item in
                    // Create grid items with a rounded rectangle
                    RoundedRectangle(cornerRadius: 10)
                        .fill(Color.blue)
                        .frame(width: 100, height: 100) // Fixed size for each grid item
                        .overlay(
                            Text("\(item)")
                                .font(.largeTitle)
                                .foregroundColor(.white) // Display item number on top
                        )
                }
            }
            .padding() // Add padding around the grid
        }
    }
}

struct ContentView: View {
    var body: some View {
        LazyHGridExample() // Show LazyHGrid layout in the main view
    }
}

@main
struct LazyHGridApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView() // Main content view
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The full series is available on my profile and the components can also be found at shipios.app/components.

Happy Coding! 🎨

Top comments (0)