我目前正在尝试构建一个菜单栏应用程序。因此,我需要一个 NSWindowController 作为登录字段。必须可以在按下菜单项时打开此 NSWindowController,并在用户单击取消时关闭该窗口。
我使用了 showWindow(self)
和 NSApp.hide(self)
但这对我不起作用。那么有人知道我可以尝试什么吗?
最佳答案
假设您正在使用 Storyboard
- 将
NSWindowController
添加到 Storyboard并取消选中窗口的visible at launch
。 在
AppDelegate
中创建一个属性windowController
var windowController : NSWindowController!
在
AppDelegate
中创建一个IBAction
。在 Action 中获取主 Storyboard
let mainStoryBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
然后实例化并分配窗口 Controller (标识符必须与 Storyboard标识符匹配)
windowController = mainStoryBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "Login")) as! NSWindowController
获取关联的 View Controller (
LoginController
是 View Controller 的自定义类)let loginController = windowController.window!.contentViewController as! LoginController
显示主窗口
windowController.showWindow(self)
在 Interface Builder 中,将
NSMenuItem
连接到First Responder
(红色立方体),然后连接到创建的IBAction
。
您可以使用红色的关闭
按钮关闭窗口,或者您需要添加自定义逻辑。
如果您使用 XIB 创建一个 NSWindowController
子类并使用 windowController = MyWindowController(window: nil)
加载 XIB,使用 NSApp.activate 激活您的应用(ignoringOtherApps: true)
使用 let controllerWindow = windowController.window!
获取关联窗口并使用 controllerWindow.makeKeyAndOrderFront(self)
关于swift - 带有 NSWindowController 的菜单栏应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49238371/