OSX status menu not working in Swift

前端 未结 1 1159
孤街浪徒
孤街浪徒 2021-02-06 17:18

I tried to add a simple status menu to the status bar with swift but it will not be shown.

with objective-c this worked:


AppDelegate.h

@int         


        
1条回答
  •  一整个雨季
    2021-02-06 17:46

    The problem here is that statusItem is going out of scope after applicationDidFinishLaunching finishes execution which in turn releases the object. This is not the case in your Objective-C code because the statusItem variable is declared at class level.

    This should make your Swift code work:

    class AppDelegate: NSObject, NSApplicationDelegate {
    
        @IBOutlet var statusMenu: NSMenu;
        var statusItem: NSStatusItem?;
    
        func applicationDidFinishLaunching(aNotification: NSNotification?) {
            let bar = NSStatusBar.systemStatusBar()
    
            statusItem = bar.statusItemWithLength(CGFloat(NSVariableStatusItemLength))
            statusItem!.title = "Status Menu"
            statusItem!.menu = statusMenu
            statusItem!.highlightMode = true
        }
    
    }
    

    0 讨论(0)
提交回复
热议问题