How to auto-resize a SwiftUI sheet on macOS to fit its content?

Consider this code that presents a sheet on macOS:

Code Block swift
struct ContentView: View {
    @State var showSheet = false
    var body: some View {
        VStack {
            Text("Hello, world!").padding()
            Button("Show sheet") {
                showSheet = true
            }
        }
        .sheet(isPresented: $showSheet) {
            SheetView()
        }
    }
}
struct SheetView: View {
    @State var greenBiggerBox = false
    var body: some View {
        VStack {
            Toggle("Show bigger box", isOn: $greenBiggerBox)
            if greenBiggerBox {
                Rectangle().frame(width: 640, height: 480).foregroundColor(.green)
            } else {
                Rectangle().frame(width: 320, height: 240).foregroundColor(.red)
            }
        }.padding()
    }
}


The problem: initially, the sheet is presented, sized correctly to its contents (good). However, when something happens inside the sheet that resizes the content (like the toggle in the sheet), the sheet window is not resized, yielding a sheet size that is either too large or too small.

How do I make the sheet resize correctly and automatically if its the size of its content changes?

Accepted Reply

It appears that this was fixed in one of the recent Big Sur betas. My sheets now resize to their content correctly.

Replies

I should also say that it works as expected and resizes the sheet on Catalina. It does not work as expected and has this error on Big Sur.
It appears that this was fixed in one of the recent Big Sur betas. My sheets now resize to their content correctly.