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) {
                .frame(minWidth: 0, maxWidth: .infinity)
                .frame(minWidth: 0, maxWidth: .infinity)

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.