How do I close a window programmatically from a Button in SwiftUI?

I have a macOS app window where I present a sheet that lets a user login to a server. When the user selects the cancel login option, I would like the sheet to be dismissed and the hosting window closed. I know how to dismiss the sheet. How do I close the window?
Answered by Claude31 in 653316022
If you have defined

Code Block
let myWindow:NSWindow?

then call

Code Block
self.myWindow?.close()

More details here:
https://stackoverflow.com/questions/58494700/swiftui-on-mac-close-window-and-open-another-one

To dismiss the sheet, 2 options:
  • environment var

  • binding to hold status of sheet

as explained here:
https ://www.hackingwithswift .com/quick-start/swiftui/how-to-make-a-view-dismiss-itself

Accepted Answer
If you have defined

Code Block
let myWindow:NSWindow?

then call

Code Block
self.myWindow?.close()

More details here:
https://stackoverflow.com/questions/58494700/swiftui-on-mac-close-window-and-open-another-one

To dismiss the sheet, 2 options:
  • environment var

  • binding to hold status of sheet

as explained here:
https ://www.hackingwithswift .com/quick-start/swiftui/how-to-make-a-view-dismiss-itself

This only works if I create my own window. I am relying on the SwiftUI app's default create window function. There is another suggestion in the link where
Code Block
NSApplication.shared.keyWindow?.close()
is suggested. This works.

You can use the dismiss environment value.

@Environment(\.dismiss) var dismiss
How do I close a window programmatically from a Button in SwiftUI?
 
 
Q