macosswiftui

How to make window resizable?


I have the following super-simple app in SwiftUI on macOS.

   var body: some Scene {
        WindowGroup {
           Text("test")
        }
        Settings {
            Rectangle()
                .fill(Color.red)
        }
   }

When I launch the app and open settings, the settings window is not resizable (main app window is, but Settings window isn't). I want settings window to have fixed width and resizable height. How to do it?


Solution

  • From the documentation of windowResizability,

    The default value for all scenes if you don’t apply the modifier is automatic. With that strategy, Settings windows use the contentSize strategy, while all others use contentMinSize.

    It sounds like putting .windowResizability(.contentMinSize) on a Settings scene would make it resizable in the same way as other windows. However, this doesn't actually work - the actual NSWindow still lacks the .resizable style mask. I'm not sure if this is intentional.

    As a workaround, you can manually add the .resizable style mask using an NSViewRepresentable.

    struct EnableWindowResize: NSViewRepresentable {
        class Helper: NSView {
            override func viewDidMoveToWindow() {
                super.viewDidMoveToWindow()
                window?.styleMask.insert(.resizable)
            }
        }
        
        func makeNSView(context: Context) -> some NSView { Helper() }
        
        func updateNSView(_ nsView: NSViewType, context: Context) { }
    }
    
    Settings {
        VStack {
            Text("Some Content")
            Spacer()
            Text("Some Other Content")
        }
        .background { EnableWindowResize() }
    }
    .windowResizability(.contentMinSize)