簡體   English   中英

在 macOS 的狀態欄應用程序上創建一個窗口

[英]Create a Window on a status bar app for macOS

警告:macOS 開發初學者在這里。

我有一個菜單欄應用程序(沒有停靠欄)。 該應用程序的大部分功能都在菜單中(並且實現在 AppDelegate 中),但我需要一個單獨的窗口,一旦我單擊其中一個菜單項,就會打開該窗口。

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

我還沒有找到合適的方法來做到這一點。 需要創建哪些文件和類似文件? 如何以編程方式打開此窗口?

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

您必須以編程方式創建一個窗口。 我附上了我的一個應用程序的示例代碼:

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函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM