【问题标题】:Create a Window on a status bar app for macOS在 macOS 的状态栏应用程序上创建一个窗口
【发布时间】:2020-06-05 18:51:07
【问题描述】:

警告:这里是 macOS 开发初学者。

我有一个菜单栏应用程序(没有停靠栏)。该应用程序的大部分功能都在菜单中(并且实现在 AppDelegate 中),但我需要一个单独的窗口,一旦我单击其中一个菜单项就会打开。

我想使用 SwiftUI、Swift 5、Xcode 11.3。

我还没有找到合适的方法来做到这一点。需要创建哪些文件和类似文件?如何以编程方式打开此窗口?

@objc func openPreferences() {
  // open a new window here...
}

【问题讨论】:

    标签: swift macos


    【解决方案1】:

    您必须以编程方式创建一个窗口。我附上了我的一个应用程序的示例代码:

    private var windowController: NSWindowController?
    
    fileprivate func createWindow()
    {
        let storyboard = NSStoryboard(name: "Main", bundle: nil)
    
        self.windowController = storyboard.instantiateInitialController() as? NSWindowController
    
        // This is example code to show how to customize the hosted view controller. You can pass additional arguments here (may an important global variables that is declared in the AppDelegate).
        if let contentController = windowController?.contentViewController as? MyWindowViewController
        {
            // Do some assignments here
            // contentController.variable = ....
            // self.windowViewController = contentController // Maybe save for later use.
        }
    }
    
    @objc fileprivate func open()
    {
        if self.windowViewController == nil
        {
            self.createWindow()
        }
    
        self.windowController?.showWindow(self)
    
        NSApp.activate(ignoringOtherApps: true) // Bring window to front.
    }
    

    我已将 open() 函数链接到按钮调用(因此使用了 @objc 关键字)。我认为你已经这样做了,所以我的 open() 函数将是你的 openPreferences 函数。

    【讨论】:

    • 谢谢,这正是我所需要的。不过有几个问题:1) 你能提供一个非常简单的MyWindowViewController 实现吗? self.windowController 是什么?
    • windowControllerAppDelegate 的全局变量。您使用此变量来保存实例。 NSWindowViewController 是NSViewController 类型的实例。这是实现您的首选项对话框逻辑的地方(控制逻辑,例如复选框上的设置值等)。 MyWindowViewController 在这里可以是可选的,如果你想传递一些数据,你只需要 AppDelegate 中的这个实例(对于简单的首选项对话框,你可能不会这样做)。
    • 什么是self.windowViewControllerself.windowViewController?.view.window?.windowControllerself.windowController 一样吗?
    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多