swift - 带有 NSWindowController 的菜单栏应用

标签 swift macos cocoa menubar nswindowcontroller

我目前正在尝试构建一个菜单栏应用程序。因此,我需要一个 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/

相关文章:

ios - TouchID activateTouchWithResponse 返回成功而不请求指纹

ios - swift UITableView : Datasource assigning Issue

macos - MacOS Catalina 上的 sed/gsed 无法按预期与 star 一起工作

cocoa - 运行命令行工具时的 NSTask 和参数

ios - swift:将字符串转换为 double 时出现问题

ios - 不能在 drawRect 中使用颜色透明度

swift - 协议(protocol)报告为有 'Self or associated type requirements' ,当它没有任何

python - 如何在Mac上记录鼠标点击以便由Apple脚本重播?

macos - OS X Terminal.app 上的 Vim Solarized 颜色不正确

objective-c - 通过套接字与 ESMTP 协商 TLS