How to close another window

I know how to close the current window. For instance, I can put that in their ViewController.swift:


@IBAction func closeSelf(_ sender: NSButton) {

self.view.window?.close()

}


But how can I close another window with a button that is in the ViewController.swift?

Accepted Reply

You need to have a reference to this other window and call close on it.

Or use notification:

In the other window viewController

- subscribe to a notification (let's call it callForClose)

- answer to this notification by closing the window


From the first window Controller:

- post a notification.

- you can add userData to reference the controller that needs to answer (not needed if other window viewController is the only subscriber to this notification).

Replies

You need to have a reference to this other window and call close on it.

Or use notification:

In the other window viewController

- subscribe to a notification (let's call it callForClose)

- answer to this notification by closing the window


From the first window Controller:

- post a notification.

- you can add userData to reference the controller that needs to answer (not needed if other window viewController is the only subscriber to this notification).

I understand the notification method and it works well.


I also would like to learn how to have a reference for the other window.

What I usually do is:

- create a class I call Global, that has a singleton


class Global {
   
    class var shared : Global {
        struct Singleton {
            static let instance = Global()
        }
        return Singleton.instance;
    }                               // shared
   
        // Reference to controllers
    var otherController : NSWindowController?      // In fact, must be the class you declared for the windowController


When I load the other class, I set it in didLoad:

Global.shared.otherController = self


Now I can use it as needed in first controller (just care for nil with conditional ?)


Global.shared.otherController?.close()     // I think you dont need Global.shared.otherController>.window.close()