[英]How to reopen an macos App using menubar button
I created an app with a menubar button using swift and storyboard, when I click the close button the window closed and the menubar button still sits on the menubar, that's good.我使用 swift 和情节提要创建了一个带有菜单栏按钮的应用程序,当我单击关闭按钮时,窗口关闭并且菜单栏按钮仍然位于菜单栏上,这很好。 What I want to do next is reopen the window by clicking the menubar button.
我接下来要做的是通过单击菜单栏按钮重新打开窗口。 After searching I figured out I can use this code to bring it to the front, but it only works when the window is still open.
搜索后我发现我可以使用此代码将其带到前面,但它仅在窗口仍打开时才有效。 How can I bring it back when it is closed or miniatured?
当它关闭或缩小时,我怎样才能把它带回来?
NSApplication.shared.activate(ignoringOtherApps: true)
This the appDelegate这是 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)
}}
This is the windowcontroller这是窗口控制器
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
}}
Thanks谢谢
I got it.我知道了。 In appdelegate use deminiaturize function does exactly what I want.
在 appdelegate 中使用 deminiaturize 函数正是我想要的。
for window in NSApp.windows {
window.deminiaturize(nil)
}
Since I only have one window but NSApp.windows has two members, I think I can deminiatureize all the windows.由于我只有一个窗口,但 NSApp.windows 有两个成员,我想我可以对所有窗口进行小型化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.