我尝试使用swift向状态栏添加一个简单的状态菜单,但不会显示.
与Objective-c一起工作:
AppDelegate.h
@interface AppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSMenu *statusMenu;
NSStatusItem * statusItem;
}
@end
Run Code Online (Sandbox Code Playgroud)
AppDelegate.m
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[statusItem setMenu:statusMenu];
[statusItem setTitle:@"Status Menu"];
[statusItem setHighlightMode:YES];
}
@end
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试在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
}
}
Run Code Online (Sandbox Code Playgroud)
没有错误,它只是没有做任何事情.函数applicationDidFinishLaunching被调用,因为它内部的println()创建输出.
有谁知道我在这里做错了什么?
lem*_*ojo 13
这里的问题是statusItem在applicationDidFinishLaunching完成执行后超出范围,反过来释放对象.在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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3018 次 |
| 最近记录: |