4

I have a simple Cocoa Application that launches a NSWindow when an NSMenu item is clicked. I am initiating the window via a segue. The problem is when I click the menu item multiple times it keeps creating new windows instead of bringing the existing window to the foreground. How can I prevent this behavior? Thanks in advance.

django-d
  • 2,210
  • 3
  • 23
  • 41

2 Answers2

9
  1. Select destination window controller
  2. Click attribute inspector and select under Presentation "Single" instead of "Multiple"

Single window instance

Marek H
  • 5,173
  • 3
  • 31
  • 42
5

If you have your Window without using Storyboard, lets say you created separate .xib and ViewController to this .xib, you could use the following approach:

Add to your class:

lazy var testViewcontroller = TestViewController(nibName: "TestWindow", bundle: nil)
lazy var testWindow = NSWindow(contentViewController: testViewcontroller)

Then, add this to the method where you invoke the window:

testWindow.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true) // will help your window to open on top of others
slava13
  • 51
  • 1
  • 4
  • Nice answer. Just why is NSApp.activate necessary? PS: the app is already active. – Marek H Apr 17 '21 at 07:28
  • @MarekH Thanks. If you want your window to open on top of others and not be lost behind others - then yes. In my case, I have just the NSStatuItem app -> when you click on it there is a list of NSMenuItems, and then by clicking a specific MenuItem window opens and I don't want this window to be lost somewhere behind others (especially when it's a small window. :) – slava13 Apr 17 '21 at 09:35
  • 1
    I can confirm NSApp.activate(ignoringOtherApps: true) is required for menubar apps as they have different activation policy. However, I think those commands should be reordered. – Marek H Apr 18 '21 at 08:18