I want to dismiss a window when a user presses a button. I have tried the @Environment
dismissWindow, however that's macOS 14+. My app requires compatibility with macOS 13 at minimum.
Dismiss window with an ID on macOS <14
Did you consider using NSNotification instead ?
- addObserver in the window, which will close it
Declare at top level (outside any class)
public static let kForceClose = Notification.Name("forceClose")
In viewDidLoad of the NSWindowController:
NotificationCenter.default.addObserver(self, selector: #selector(closeIt(_:)), name: .kClose, object: nil)
@objc func forceClose(_ sender: Notification) {
self.window?.close()
}
- Send notification in Button IBAction
NotificationCenter.default.post(name: .kForceClose, object: self)