SwiftUI – why is my Mac window not resizable?

As a newbie to SwiftUI, I was surprised to find my simple little sample application would not resize. If you’re used to WPF, WinForms and even other non-Windows user interface libraries, you’ll notice by default the windows are usually resizable. So what’s the deal with SwiftUI

So my code looked like this

var body: some View {
   VStack {
      Text(viewModel.title)
         .padding()
      TextField("Enter", text: $viewModel.title)
   }
   .padding()
   .frame(minWidth: 500, minHeight: 300)
}

Simple enough, display a text label and input text field.

So what’s the problem, why is the Man window not resizable?

Spacer

The Spacer is key here. If we change the code to the following, the it all starts to work as I wanted

var body: some View {
   VStack {
      Text(viewModel.title)
         .padding()
      TextField("Enter", text: $viewModel.title)
      Spacer()
   }
   .padding()
   .frame(minWidth: 500, minHeight: 300)
}

The Spacer expands to fill space.

If you have a Spacer within a VStack the spacer fills space on the vertical and if on an HStack it fills horizontally. But the above code will expand on both the vertical and horizontal. In this case the TextField seems to combine with the Spacer to allow both the axis to expand.