单击时防止 NSMenu 创建同一 NSWindow 的多个实例

Prevent NSMenu from creating multiple instances of same NSWindow when clicked

我有一个简单的 Cocoa 应用程序,它在单击 NSMenu 项时启动 NSWindow。我正在通过 segue 启动 window。问题是当我多次单击菜单项时,它会不断创建新的 windows,而不是将现有的 window 置于前台。我怎样才能防止这种行为?提前致谢。

  1. Select 目的地 window 控制器
  2. 单击属性检查器并单击 Presentation "Single" 下的 select 而不是 "Multiple"

如果您的 Window 没有使用 Storyboard,假设您为此 .xib 创建了单独的 .xib 和 ViewController,您可以使用以下方法:

添加到您的class:

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

然后,将其添加到调用 window 的方法中:

testWindow.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true) // will help your window to open on top of others