Enter LazyVGrid and LazyHGrid — SwiftUI’s powerful grid-based layout system. In this post, you’ll learn how to create responsive, performant, and adaptive grids for your apps.
Why Use Grids in SwiftUI?
- Adaptive layouts: Easily adjust columns and rows based on screen size.
- Lazy loading: SwiftUI loads only the visible elements, improving performance.
- Flexible customization: Define spacing, alignment, and sizing for your grids.
Understanding Grid Layouts in SwiftUI
- LazyVGrid: Creates a vertical grid (columns) inside a ScrollView.
- LazyHGrid: Creates a horizontal grid (rows) inside a ScrollView.
Both grids require a GridItem array to define their structure.
Creating a Basic LazyVGrid
- GridItem(.fixed(100)) defines two columns of fixed width (100pt).
- LazyVGrid lays out views vertically.
- ScrollView ensures scrolling when content exceeds screen height.
Adaptive Columns: Responsive Grids
- GridItem(.adaptive(minimum: 80)) automatically creates as many columns as can fit in the available space.
- If there's more space, more columns appear dynamically.
Creating a LazyHGrid
- LazyHGrid arranges items horizontally, requiring a ScrollView(.horizontal).
- rows define the number of horizontal sections.
Mixing Fixed and Flexible Grid Items
- First column is always 100pt wide.
- Second column expands to use available space.
- Third column adapts dynamically based on available width.
Building a Photo Gallery with LazyVGrid
Important: Make sure to add images to your project's Assets Catalog with the names photo1.jpg to photo15.jpg for this example to work correctly.
- Adaptive Grid Layout: Images adjust dynamically with GridItem(.adaptive(minimum: 100, maximum: 150)).
- Zoom Animation: Clicking an image enlarges it slightly with scaleEffect.
- Fullscreen Preview: Clicking an image opens it in full view with a fade effect.
- Dark Mode UI: A black background ensures high contrast.
- Use LazyVGrid for vertical lists and LazyHGrid for horizontal ones.
- Adaptive columns allow grids to adjust dynamically.
- Mixing fixed, flexible, and adaptive layouts provides ultimate control.
- Grids are ideal for photo galleries, dashboards, and data-heavy views.
By mastering SwiftUI’s grid system, you can create powerful, flexible, and efficient layouts with minimal code.
Next week, we’ll explore ZStacks and Overlays, learning how to layer views for stunning visual effects. Get ready to add depth and dimension to your SwiftUI layouts!