SwiftUI: Two equal width columns

June 17, 2020

A problem that many people run into after writing enough SwiftUI is how to make it so that two views inside an HStack have equal width, such that if the HStack grows both inner views expand proportionally.

There are several articles online talking about how to do this with GeometryReader or preferences, but for the common case of just having columns equally distributed, it's actually easier to just use frames. If you set the views' frames to both have a min width of 0 and max width of infinity, SwiftUI's layout system distributes them equally:

struct ContentView: View {
    var body: some View {
        HStack(alignment: .top, spacing: 0) {
            Rectangle()
                .fill(Color.blue)
                .frame(minWidth: 0, maxWidth: .infinity)
            Rectangle()
                .fill(Color.red)
                .frame(minWidth: 0, maxWidth: .infinity)
        }.padding().background(Color.white)
    }
}

This produces the result we want regardless of screen size:

Red and blue squares filling space equally on a small screen
Red and blue squares filling space equally on a large screen

Hopefully this helps you simplify your SwiftUI code for when you only need to account for the common case of two columns 👍

Sample code for this project is available at NGSwiftUIEqualWidthColumnExample.

Picture of me with a corgi

Noah Gilmore

Hello! I'm Noah, a software developer based in the San Francisco bay area. I focus mainly on iOS, Apple platform development, and full stack web development.

  • 💻 I'm writing a macOS editor for Atlassian Confluence called Fluency
  • 📱 I wrote an app which lets you create transparent app icons called Transparent App Icons
  • 🧩 I made a puzzle game for iPhone and iPad called Trestle
  • 🎨 I wrote a CoreImage filter utility app for iOS developers called CIFilter.io
  • 👋 Please feel free to reach out on Twitter