我正在尝试用Swift构建一个框架应用程序,在那里我基本上只有一个菜单栏图标,没有窗口。从Xcode中的一个新故事板项目开始,它开始工作,但为了摆脱窗口,它似乎不想再运行了。我有以下几点:
import Cocoa
import AppKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window = NSWindow()
var statusBar = NSStatusBar.systemStatusBar()
var statusBarItem : NSStatusItem = NSStatusItem()
override func awakeFromNib() {
statusBarItem = statusBar.statusItemWithLength(-1)
statusBarItem.title = "Test"
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
sleep(10);
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
在appdelegate.swift中(基于this tutorial)。通过xcode运行时,我会收到一些警告:
2015-06-23 22:20:28.444 PENCloud[19491:3303755] Failed to connect (colorGridView) outlet from (NSApplication) to (NSColorPickerGridView): missing setter or instance variable
2015-06-23 22:20:28.444 PENCloud[19491:3303755] Failed to connect (view) outlet from (NSApplication) to (NSColorPickerGridView): missing setter or instance variable
从一些谷歌搜索中,我似乎可以忽略这些,但我的
statusBarItem
不再出现。我错过了什么? 最佳答案
您需要使用下面的代码main.swift
。
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var statusBarItem : NSStatusItem!
func applicationDidFinishLaunching(aNotification: NSNotification) {
statusBarItem = statusBar.statusItemWithLength(-1)
statusBarItem.title = "Test"
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
autoreleasepool { () -> () in
let app = NSApplication.sharedApplication()
let delegate = AppDelegate()
app.delegate = delegate
app.run()
}
文件名必须是
main.swift
。否则,您将在autoreleasepool行上得到错误Expressions are not allowed at the top level
。我在这里找到了答案:
https://stackoverflow.com/a/26322464/338986