Search code examples
swiftxcodemacoscocoa

How to Regain/Set Focus in a Mac OS Swift Application


In one of my views I called a modal dialog like the:

let application = NSApplication.shared()
application.runModal(for: artistDialogWindow)

When the OK or Cancel button are pressed, I terminate the modal window like this:

let application = NSApplication.shared()
application.stopModal()

The view that called the dialog regains control. After it runs so code, it exits. On the screen, it appears that no window has focus. If I click on the title bar of my window, the red, orange, and green buttons on the left of the title bar go from gray to color. How can I do this programmatically?

I tried NSApplication.activate. It doesn't do anything. Presumably my app is already active. It just doesn't have focus. I also tried selecting a row in a table in the view. The row is selected, but the window is not.


Solution

  • You could try NSWindow's makeKey(). Or makeKeyAndOrderFront(_ sender: Any?). These activate the window.

    For example, a niceWindow has to be focused (you need a reference to the window that you want to bring focus to). Then do:

    niceWindow.makeKey()
    

    or

    niceWindow.makeKeyAndOrderFront(self)