问题
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