簡體   English   中英

如何使用菜單欄按鈕重新打開 macOS 應用程序

[英]How to reopen an macos App using menubar button

我使用 swift 和情節提要創建了一個帶有菜單欄按鈕的應用程序,當我單擊關閉按鈕時,窗口關閉並且菜單欄按鈕仍然位於菜單欄上,這很好。 我接下來要做的是通過單擊菜單欄按鈕重新打開窗口。 搜索后我發現我可以使用此代碼將其帶到前面,但它僅在窗口仍打開時才有效。 當它關閉或縮小時,我怎樣才能把它帶回來?

NSApplication.shared.activate(ignoringOtherApps: true)

這是 appDelegate

class AppDelegate: NSObject, NSApplicationDelegate {

private var statusItem: NSStatusItem!

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    
    statusItem = NSStatusBar.system.statusItem(withLength: 16.0)
    if let button = statusItem.button {
        button.image = NSImage(named: "remote-control")
        button.image?.size = NSSize(width: 16.0, height: 16.0)
        button.image?.isTemplate = true

        button.action = #selector(bringToFront(sender:))
    }
}

func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
    print("terminate")
}

func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
    return true
}

@objc func bringToFront(sender: AnyObject?) {
    NSApplication.shared.activate(ignoringOtherApps: true)
    NSApp.windows.last?.makeKeyAndOrderFront(nil)
}}

這是窗口控制器

class MainWindowController: NSWindowController {

override func windowDidLoad() {
    super.windowDidLoad()

    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    
    window?.title = ""
    let styleMask: NSWindow.StyleMask = [.closable, .titled, .miniaturizable]
    window?.styleMask = styleMask
}}

謝謝

我知道了。 在 appdelegate 中使用 deminiaturize 函數正是我想要的。

    for window in NSApp.windows {
        window.deminiaturize(nil)
    }

由於我只有一個窗口,但 NSApp.windows 有兩個成員,我想我可以對所有窗口進行小型化。

暫無
暫無

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

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