0

我正在创建一个应用程序,它只存在于菜单栏中,但是如果用户未登录,我希望弹出一个全尺寸的普通窗口,我制作了一个小弹出窗口,这对我来说已经足够了要进入的主应用程序:

在此处输入图像描述

我用来实现此目的的代码:

class AppDelegate: NSObject, NSApplicationDelegate{

var statusItem: NSStatusItem?
var popOver = NSPopover()

func applicationDidFinishLaunching(_ notification: Notification) {
    
    let menuView = MenuView().environmentObject(Authentication())
    
    popOver.behavior = .transient
    popOver.animates = true
    popOver.contentViewController = NSViewController()
    popOver.contentViewController?.view = NSHostingView(rootView: menuView)
    
    popOver.contentViewController?.view.window?.makeKey()
    
    statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    
    if let MenuButton = statusItem?.button{
        
        MenuButton.image = NSImage(systemSymbolName: "gearshape.fill", accessibilityDescription: nil)
        MenuButton.action = #selector(MenuButtonToggle)
        
    }
    
    if let window = NSApplication.shared.windows.first {
        window.close()
    }
}

@objc func MenuButtonToggle(sender: AnyObject? = nil){
    
    if popOver.isShown{
        popOver.performClose(sender)
    }
    else{
        if let menuButton = statusItem?.button{
            NSApplication.shared.activate(ignoringOtherApps: true)
            self.popOver.show(relativeTo: menuButton.bounds, of: menuButton, preferredEdge: NSRectEdge.minY)
            
        }
    }
}

@objc func closePopover(_ sender: AnyObject? = nil) {
    popOver.performClose(sender)
}

@objc func togglePopover(_ sender: AnyObject? = nil) {
    if popOver.isShown {
        closePopover(sender)
    } else {
        MenuButtonToggle(sender: sender)
    }
}
}

我在 AppDelegate 中制作了弹出视图,我想渲染它(在菜单栏中带有图标)或只是一个普通的 macOS 窗口(在菜单栏中没有图标)。然后可以通过以下方式轻松地在两者之间切换:

if session != nil{
    // show menu bar style
else{

    // show window view to log in
}
4

0 回答 0