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.
Asked
Active
Viewed 1,087 times
2 Answers
9
- Select destination window controller
- Click attribute inspector and select under Presentation "Single" instead of "Multiple"

Marek H
- 5,173
- 3
- 31
- 42
-
1
-
-
-
What should I do if I don't use segue ? Just programmatically init window after pressing on context menu button – Roman Bobelyuk Jul 03 '20 at 06:30
-
This case means you do memory management yourself -> you know if you created it before. Your question is more like how to create window with viewcontroller. – Marek H Jul 04 '20 at 09:59
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
-
1I 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