Build a Responsive Square-Cell Grid in SwiftUI
BehavioralModel answerLast updated
Construct a three-column scrollable grid where each cell maintains a 1:1 aspect ratio and responds to screen size changes, with navigation to a detail screen.
Challenge
You need to build a photo gallery interface for an iOS app. The interface displays a collection of images in a grid format with specific layout requirements.
Your Task
Implement a scrollable grid view that arranges image items in a three-column layout. Every cell must be perfectly square—its height must equal its width—regardless of device screen dimensions or orientation.
Core Requirements
- Column Structure: Display exactly three columns of items, distributed evenly across the available screen width
- Square Geometry: Each cell must maintain a 1:1 aspect ratio automatically as the screen width changes
- Navigation Flow: When a user taps any cell, navigate to a detail screen showing that image
- Reactive Data: The grid should respond to changes in the underlying data source, updating the display appropriately
- Efficiency: Use lazy rendering so that only visible cells (plus a small buffer) are instantiated, not the entire dataset
Implementation Guide
You'll create a SwiftUI view with this structure:
struct PhotoGalleryGrid: View {
let imageIdentifiers: [String]
var body: some View {
// Your implementation
}
}
Behavior Example
Given imageIdentifiers = ["photo_a", "photo_b", "photo_c", "photo_d", "photo_e"]:
- The grid renders two rows: the first with three cells, the second with two
- Each cell occupies exactly one-third of the available width (accounting for spacing)
- Cell heights automatically match their widths
- Tapping the first cell navigates to a detail view displaying
"photo_a"
Technical Constraints
- No hardcoded pixel dimensions—the layout must adapt to any screen size
- Support both portrait and landscape orientations seamlessly
- The grid must scroll vertically when content exceeds the viewport height
- Images may have varying native aspect ratios but must appear square in the grid
Hints
Hint 1
Use LazyVGrid with flexible columns to distribute width evenly while maintaining lazy rendering
Hint 2
Apply aspectRatio modifier to a base shape rather than directly to the image to ensure square cells
Hint 3
Combine aspectRatio with scaledToFill and clipped to crop images to the square boundary
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The challenge requires balancing three competing concerns: dynamic layout, performance, and precise geometric constraints. The solution uses SwiftUI's LazyVGrid with a strategic layering pattern to achieve square cells.
Architecture
Layout Foundation: A LazyVGrid with three .flexible() columns automatically divides the horizontal space equally. When combined with ScrollView, it provides vertical scrolling and only instantiates views near the visible region—critical for large datasets.
Square Constraint: The subtle part is achieving square cells. Applying .aspectRatio(1, contentMode: .fit) directly to an image fails because images have intrinsic sizes that influence layout. Instead, use a neutral base layer (like Color) with the aspect ratio modifier, then overlay the image. The base establishes the square boundary; the image fills it with .scaledToFill() and .clipped().
Navigation: SwiftUI's value-based navigation (NavigationLink(value:) with .navigationDestination) avoids creating detail views eagerly for every cell, improving performance.
State Management: The grid is a pure view of its input array. An ObservableObject publishes changes, and SwiftUI's diffing updates only affected cells.
Implementation
import SwiftUI
// MARK: - Grid View
struct PhotoGalleryGrid: View {
let imageIdentifiers: [String]
private let cellSpacing: CGFloat = 2
private var gridColumns: [GridItem] {
Array(repeating: GridItem(.flexible(), spacing: cellSpacing), count: 3)
}
var body: some View {
NavigationStack {
ScrollView {
LazyVGrid(columns: gridColumns, spacing: cellSpacing) {
ForEach(imageIdentifiers, id: \.self) { identifier in
NavigationLink(value: identifier) {
GridCell(imageIdentifier: identifier)
}
.buttonStyle(.plain)
}
}
}
.overlay {
if imageIdentifiers.isEmpty {
Text("No photos")
.foregroundStyle(.secondary)
}
}
.navigationTitle("Gallery")
.navigationDestination(for: String.self) { identifier in
PhotoDetailView(imageIdentifier: identifier)
}
}
}
}
// MARK: - Individual Cell
struct GridCell: View {
let imageIdentifier: String
var body: some View {
Color.gray.opacity(0.1)
.aspectRatio(1, contentMode: .fit) // base: makes height = width
.overlay {
Image(imageIdentifier)
.resizable()
.scaledToFill() // fills square, cropping excess
}
.clipped() // trims overflow
.contentShape(Rectangle()) // constrains tap area
.accessibilityLabel("Photo \(imageIdentifier)")
}
}
// MARK: - Detail Screen
struct PhotoDetailView: View {
let imageIdentifier: String
var body: some View {
Image(imageIdentifier)
.resizable()
.scaledToFit()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
.navigationTitle(imageIdentifier)
.navigationBarTitleDisplayMode(.inline)
}
}
// MARK: - Data Management
final class GalleryData: ObservableObject {
@Published private(set) var identifiers: [String] = []
func append(_ id: String) {
guard !identifiers.contains(id) else { return }
identifiers.append(id)
}
func removeAll() {
identifiers.removeAll()
}
func replaceWith(_ newIDs: [String]) {
var uniqueSet = Set<String>()
identifiers = newIDs.filter { uniqueSet.insert($0).inserted }
}
}
Why This Works
Three Columns: Each GridItem(.flexible()) claims an equal share of available width after accounting for spacing. With three items, each gets (totalWidth - 2 × spacing) / 3.
Perfect Squares: The Color base has no intrinsic size, so .aspectRatio(1, .fit) forces height to equal the width proposed by the grid. The image overlay inherits this exact size, filling and cropping as needed.
Orientation Changes: When the device rotates, the grid's available width changes, columns recompute their sizes, and aspect ratios recalculate heights—all automatically.
Lazy Loading: LazyVGrid only materializes cells within or near the scroll viewport, keeping memory proportional to screen size, not dataset size.
Reactive Updates: When identifiers changes, SwiftUI diffs by identity. Cells for unchanged IDs persist; new IDs trigger cell creation; removed IDs trigger destruction.
Complexity Analysis
Let n = total items, v = visible cells on screen.
- Memory: O(v) — only visible and buffered cells exist
- Initial render: O(v) — SwiftUI constructs views for the visible region
- Data update: O(n) for identity diff, O(changed) for view updates
- Scroll: O(newly visible) as cells enter/exit the viewport
Edge Cases and Tradeoffs
Empty State: Display placeholder text rather than a blank screen.
Partial Last Row: If the dataset isn't a multiple of three, the last row contains 1–2 cells. Each still occupies one-third width—they don't stretch to fill the row.
Duplicate Identifiers: Using id: \.self with duplicates causes diffing instability. The data layer enforces uniqueness. For production, use Identifiable models with stable UUIDs.
Non-Square Images: Fill-and-clip handles any aspect ratio. Tall images lose top/bottom; wide images lose left/right. If you need smart cropping (face detection, etc.), preprocess thumbnails.
Wide Screens (iPad, Landscape): Three columns create large cells. For adaptive column counts, replace .flexible() with GridItem(.adaptive(minimum: 120)).
Hit Testing: Without .contentShape(Rectangle()), an image that fills beyond the clip boundary can intercept taps meant for neighboring cells.
Accessibility: Each cell gets a label for VoiceOver. Dynamic Type doesn't affect grid geometry, which is intentional—images don't reflow with text size.
Common Mistakes
- Applying aspect ratio to the image directly: The image's intrinsic size dominates, breaking the square constraint.
- Using fixed pixel heights: Breaks on different devices and orientations.
- Eager navigation: Building detail views for all cells upfront wastes memory. Use value-based navigation.
- Forgetting
.clipped(): Images overflow into adjacent cells visually. - No empty state: A blank screen looks broken; always provide feedback.
Performance Extensions
For remote images at high resolution:
- Async loading: Fetch and decode off the main thread
- Downsampling: Use
CGImageSourceCreateThumbnailAtIndexto decode at thumbnail size, not full resolution - Two-tier cache: Memory cache (
NSCache) for decoded images, disk/URL cache for raw bytes - Server thumbnails: Request smaller variants (
?size=300) instead of originals
For thousands of items, consider adding pull-to-refresh, pagination, or search filtering to reduce the rendered dataset size.