November 18, 2024
SwiftUI Grid: Better Layouts with Dynamic Grids
Build dynamic layouts using grids in SwiftUI
Alexander Adelmaer
3 min read
Using SwiftUI Grid is a smart way to build structured and visually appealing layouts in your iOS apps. Whether you're working on a photo gallery, a product list, or a custom interface, grids allow you to organize content in rows and columns effortlessly.
In this article, you'll learn:
- How to create and customize grids in SwiftUI.
- When to use LazyVGrid and LazyHGrid for better performance.
- Advanced techniques for building responsive, dynamic layouts with grids.
By the end, you'll know how to leverage grids to create layouts that look great on all devices, improving both usability and app performance.
Why Use Grids in SwiftUI?
SwiftUI Grid provides a more structured way to display content compared to stacks. Grids handle layout across both rows and columns, allowing for more complex designs.
Key Advantages:
- Two-Dimensional Layout: Organize content in rows and columns, making it easier to design professional layouts.
- Customizable Design: Control spacing, alignment, and sizing for precise layouts.
- Performance Optimization: Use lazy grids to load only visible content, making them ideal for large datasets.
Building a Simple Grid in SwiftUI
Here's how to build a simple grid with two rows and two columns:
// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct SimpleGridView: View {
var body: some View {
Grid {
GridRow {
Text("Item 1")
Text("Item 2")
}
GridRow {
Text("Item 3")
Text("Item 4")
}
}
.padding()
.border(Color.gray, width: 1)
}
}
#Preview {
SimpleGridView()
}// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct SimpleGridView: View {
var body: some View {
Grid {
GridRow {
Text("Item 1")
Text("Item 2")
}
GridRow {
Text("Item 3")
Text("Item 4")
}
}
.padding()
.border(Color.gray, width: 1)
}
}
#Preview {
SimpleGridView()
}- Grid: The container view that arranges child views in rows and columns.
- GridRow: Represents a single row. Each child view in a
GridRowbecomes a cell in the row. - Automatic Column Layout: SwiftUI automatically creates columns based on the number of views in a row.
This simple grid is a great starting point for understanding how grids work in SwiftUI.
Customizing Grid Spacing and Alignment
Grids in SwiftUI allow you to fine-tune the layout with alignment and spacing options. Here's how to customize these properties:
// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct CustomizedGridView: View {
var body: some View {
Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 10) {
GridRow {
Text("Column 1").frame(maxWidth: .infinity)
Text("Column 2").frame(maxWidth: .infinity)
}
GridRow {
Text("Data 1").frame(maxWidth: .infinity)
Text("Data 2").frame(maxWidth: .infinity)
}
}
.padding()
}
}// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct CustomizedGridView: View {
var body: some View {
Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 10) {
GridRow {
Text("Column 1").frame(maxWidth: .infinity)
Text("Column 2").frame(maxWidth: .infinity)
}
GridRow {
Text("Data 1").frame(maxWidth: .infinity)
Text("Data 2").frame(maxWidth: .infinity)
}
}
.padding()
}
}- Alignment: The
alignmentparameter controls how cells align horizontally or vertically. - Horizontal and Vertical Spacing: Adjust the spacing between cells to make the grid look polished.
- Max Width: Adding
.frame(maxWidth: .infinity)ensures cells expand to fill available space.
This makes the grid adaptable to different screen sizes, an essential feature for responsive design.
LazyVGrid: Vertical Scrolling Grids
When you need a grid for a large dataset that scrolls vertically, LazyVGrid is your go-to option. It only renders visible items, improving performance significantly.
// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct LazyVGridView: View {
let items = Array(1...20)
let columns = [
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 15) {
ForEach(items, id: \.self) { item in
Text("Item \(item)")
.frame(height: 100)
.background(Color.blue.opacity(0.7))
.cornerRadius(8)
}
}
.padding()
}
}
}
struct LazyVGridView_Previews: PreviewProvider {
static var previews: some View {
LazyVGridView()
}
}// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct LazyVGridView: View {
let items = Array(1...20)
let columns = [
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 15) {
ForEach(items, id: \.self) { item in
Text("Item \(item)")
.frame(height: 100)
.background(Color.blue.opacity(0.7))
.cornerRadius(8)
}
}
.padding()
}
}
}
struct LazyVGridView_Previews: PreviewProvider {
static var previews: some View {
LazyVGridView()
}
}- ScrollView: Wraps the grid to enable vertical scrolling.
- LazyVGrid: A grid that dynamically loads views as they come into the viewport.
- Flexible Columns: Using
.flexible()ensures columns adjust to available space, making the layout responsive.
This is ideal for creating grids like product listings or image galleries.
LazyHGrid: Horizontal Scrolling Grids
For horizontally scrolling grids, LazyHGrid works similarly but arranges content in rows instead of columns.
// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct LazyHGridView: View {
let items = Array(1...10)
let rows = [
GridItem(.fixed(80)),
GridItem(.fixed(80))
]
var body: some View {
ScrollView(.horizontal) {
LazyHGrid(rows: rows, spacing: 20) {
ForEach(items, id: \.self) { item in
Text("Item \(item)")
.frame(width: 100)
.background(Color.green.opacity(0.7))
.cornerRadius(8)
}
}
.padding()
}
}
}
struct LazyHGridView_Previews: PreviewProvider {
static var previews: some View {
LazyHGridView()
}
}// SwiftUI Grid tutorial by AppMakers.Dev
import SwiftUI
struct LazyHGridView: View {
let items = Array(1...10)
let rows = [
GridItem(.fixed(80)),
GridItem(.fixed(80))
]
var body: some View {
ScrollView(.horizontal) {
LazyHGrid(rows: rows, spacing: 20) {
ForEach(items, id: \.self) { item in
Text("Item \(item)")
.frame(width: 100)
.background(Color.green.opacity(0.7))
.cornerRadius(8)
}
}
.padding()
}
}
}
struct LazyHGridView_Previews: PreviewProvider {
static var previews: some View {
LazyHGridView()
}
}- Horizontal Scrolling: Use
.horizontalwithScrollViewfor horizontal scrolling. - Fixed Rows: Use
.fixed()for consistent row heights. - Dynamic Rendering: Only visible cells are rendered, improving performance.
Horizontal grids are useful for carousels, timelines, and more.
Advanced Techniques with Grids in SwiftUI
Spanning Grid Columns
You can make items span multiple columns for a dynamic layout:
// SwiftUI Grid tutorial by AppMakers.Dev
Grid {
GridRow {
Text("Header")
.gridCellColumns(2)
.background(Color.gray.opacity(0.3))
}
GridRow {
Text("Column 1")
Text("Column 2")
}
}// SwiftUI Grid tutorial by AppMakers.Dev
Grid {
GridRow {
Text("Header")
.gridCellColumns(2)
.background(Color.gray.opacity(0.3))
}
GridRow {
Text("Column 1")
Text("Column 2")
}
}- gridCellColumns(_:): Allows a cell to span multiple columns, useful for headers or large content blocks.
Resizing and Fixed Sizes
Prevent unwanted resizing with gridCellUnsizedAxes:
Text("Fixed Size")
.gridCellUnsizedAxes(.horizontal)Text("Fixed Size")
.gridCellUnsizedAxes(.horizontal)This is helpful when you want to ensure consistent cell sizes regardless of the grid's content.
Performance Tips for Grids
- Use Lazy Grids for Large Data: They only render visible content, reducing memory usage.
- Minimize Nested Grids: Avoid deeply nested grids for better performance.
- Profile Your Layouts: Use Xcode Instruments to identify layout bottlenecks.
Conclusion
SwiftUI Grid offers a flexible and powerful way to create dynamic, responsive layouts for your iOS apps. From simple grids with Grid to scalable layouts using LazyVGrid or LazyHGrid, grids are indispensable tools for modern app design.
You Might Be Interested In:
Thanks for Reading
๐๐ If you enjoyed and found this post useful, please clap and share it.
๐ Join AppMakers on Medium for SwiftUI, Swift & iOS App Development
๐ฉ Subscribe to our Mailing List for Updates about new articles
LEARN iOS Development ๐ท Latest SwiftUI Tutorials ๐ SwiftUI Handbook
๐ Follow the Editor for More Updates and Useful Articles
Happy Coding to You ๐ง๐ฝโ๐ป๐ฉ๐ปโ๐ป