OSX status menu not working in Swift

≯℡__Kan透↙ 提交于 2020-01-22 10:06:24

问题


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

@interface AppDelegate : NSObject <NSApplicationDelegate> {
    IBOutlet NSMenu *statusMenu;
    NSStatusItem * statusItem;
}

@end

AppDelegate.m

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
    [statusItem setMenu:statusMenu];
    [statusItem setTitle:@"Status Menu"];
    [statusItem setHighlightMode:YES];
}

@end

But if i try to do basically the same thing in swift it doesn't do anything.

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var statusMenu: NSMenu;

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        let bar = NSStatusBar.systemStatusBar()

        let statusItem = bar.statusItemWithLength(CGFloat(NSVariableStatusItemLength))
        statusItem.title = "Status Menu"
        statusItem.menu = statusMenu
        statusItem.highlightMode = true
    }

}

There's no error, it just doesn't do anything. the function applicationDidFinishLaunching is called since a println() inside it creates output.

Does anyone have an idea what I'm doing wrong here?


回答1:


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
    }

}


来源:https://stackoverflow.com/questions/24069432/osx-status-menu-not-working-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!