与NSWindowController的菜单应用程序

时间:2018-03-12 15:02:17

标签: swift macos cocoa menubar nswindowcontroller

我目前正在尝试构建一个菜单栏应用。因此我需要一个NSWindowController作为登录字段。按下菜单项时必须可以打开这个NSWindowController,当用户点击取消时也可以关闭该窗口。

我使用showWindow(self)NSApp.hide(self),但这对我不起作用。那么有谁知道我可以尝试什么?

2 个答案:

答案 0 :(得分:1)

假设您正在使用Storyboard

  • 在故事板中添加NSWindowController,取消选中该窗口的visible at launch
  • AppDelegate中创建一个属性windowController

    var windowController : NSWindowController!
    
  • AppDelegate中创建IBAction

  • 在动作中使用

    获取主故事板
    let mainStoryBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
    
  • 然后实例化并分配窗口控制器(标识符必须与故事板标识符匹配)

    windowController = mainStoryBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "Login")) as! NSWindowController
    
  • 获取关联的视图控制器(LoginController是视图控制器的自定义类)

    let loginController = windowController.window!.contentViewController as! LoginController
    
  • 显示主窗口

    windowController.showWindow(self)
    
  • 在Interface Builder中,将NSMenuItem连接到First Responder(红色多维数据集),然后连接到创建的IBAction

您可以使用红色close按钮关闭窗口,也可以添加自定义逻辑。

如果您使用XIB创建NSWindowController子类并使用windowController = MyWindowController(window: nil)加载XIB,请使用NSApp.activate(ignoringOtherApps: true)激活您的应用,并使用let controllerWindow = windowController.window!获取相关窗口并显示窗口与controllerWindow.makeKeyAndOrderFront(self)

答案 1 :(得分:0)

抱歉,您的代码在我的项目中崩溃了。我做错了什么?

Screenshot

相关问题