LazyHGrid Grid Layout in iOS 18
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.
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
}
}
}
The full series is available on my profile and the components can also be found at shipios.app/components.
Happy Coding! 🎨
Subscribe to my newsletter
Read articles from Vaibhav directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Vaibhav
Vaibhav
From product vision to pixel-perfect execution, I'm a seasoned Product Manager turned iOS App Developer, leveraging Swift and SwiftUI to craft intuitive, user-centric experiences.