我尝试使用 swift向状态栏添加一个简单的状态菜单,但不会显示. 与Objective-c一起工作: AppDelegate.h @interface AppDelegate : NSObject NSApplicationDelegate { IBOutlet NSMenu *statusMenu; NSStatusItem * statusItem
与Objective-c一起工作:
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
但是,如果我尝试在swift中基本上做同样的事情,它什么都不做.
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 } }
没有错误,它只是没有做任何事情.调用函数applicationDidFinishLaunching,因为它内部的println()创建输出.
有谁知道我在这里做错了什么?
这里的问题是,在applicationDidFinishLaunching完成执行后,statusItem将超出范围,而执行又会释放对象.在Objective-C代码中不是这种情况,因为statusItem变量是在类级别声明的.这应该使你的Swift代码工作:
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 } }