💡 Fix Uneven Spacing in SwiftUI Stacks

Get weekly handpicked updates on Swift and SwiftUI!

TL;DR: Fix uneven spacing in VStack and HStack by explicitly setting the spacing parameter. Default spacing varies among subviews when spacing is nil. Use explicit values for consistent layouts or rely on default spacing for dynamic adjustments.

Problem

When using layout containers like VStack, HStack, or Grid in SwiftUI, developers may notice inconsistent spacing between subviews. This inconsistency can negatively impact the visual aesthetics and user experience of an app.

Analysis of the Causes

  1. Differences in Default Spacing for Views: In SwiftUI, each view or component comes with its own default spacing value.
  2. The Container’s spacing Parameter: When the spacing parameter of a layout container is set to nil, SwiftUI dynamically calculates the spacing based on the default spacing values of its child views.
  3. Source of Inconsistency: If the child views within a container have varying default spacing values, the overall spacing between subviews may appear inconsistent. For example, Text and Rectangle may have different default spacing values, resulting in uneven spacing within a layout.

Solution

Explicitly specify the spacing parameter of the container to ensure consistent spacing between subviews:

Swift
VStack(spacing: 10) {
    Rectangle()
    Text("Fat")
    Rectangle()
}

By explicitly setting the spacing, you can ensure that all subviews have uniform spacing.

Helpful Tip

SwiftUI’s default spacing system is designed to account for the following:

  • Differences across devices and platforms;
  • Dynamic adjustments based on font, component type, and context.

If the default spacing meets your design needs, you can continue using nil for the spacing parameter to leverage the system’s dynamic adjustments.

Further Reading