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! 🎨

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more