我正在尝试使用swift为OSX编写状态栏应用程序。 Objective-C中的等效代码似乎工作并显示状态栏菜单,但以下代码不会:
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var statusMenu: NSMenu
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
override func awakeFromNib() {
var statusBar = NSStatusBar.systemStatusBar()
var statusBarItem = statusBar.statusItemWithLength(CGFloat(NSVariableStatusItemLength))
statusBarItem.menu = statusMenu
statusBarItem.title = "TestApp"
}
}
答案 0 :(得分:11)
statusBarItem
对awakeFromNib()
的调用完成后,import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var statusMenu: NSMenu
var statusBarItem : NSStatusItem?
override func awakeFromNib() {
var statusBar = NSStatusBar.systemStatusBar()
statusBarItem = statusBar.statusItemWithLength(CGFloat(NSVariableStatusItemLength))
statusBarItem!.menu = statusMenu
statusBarItem!.title = "TestApp"
}
}
var超出范围,您需要保留对它的引用。尝试这样的事情:
{{1}}