KatInterview

Build a Responsive Square-Cell Grid in SwiftUI

BehavioralModel answer
HardModel answerBehavioraliosswiftuimobile-ui

Last 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

  1. Column Structure: Display exactly three columns of items, distributed evenly across the available screen width
  2. Square Geometry: Each cell must maintain a 1:1 aspect ratio automatically as the screen width changes
  3. Navigation Flow: When a user taps any cell, navigate to a detail screen showing that image
  4. Reactive Data: The grid should respond to changes in the underlying data source, updating the display appropriately
  5. 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