最小的Cocoa / Swift菜单栏应用程序不想运行

时间:2015-06-23 20:27:13

标签: xcode swift cocoa

我正在尝试在Swift中构建一个骨架应用程序,我基本上只有一个菜单栏图标,没有窗口。从Xcode中的一个新的Storyboard项目开始,它最初工作,但试图摆脱窗口,它似乎不想再运行。我有以下内容:

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不再出现。我错过了什么?

2 个答案:

答案 0 :(得分:5)

您需要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。否则,您将在自动释放池行中收到错误Expressions are not allowed at the top level

我在这里找到答案: https://stackoverflow.com/a/26322464/338986

答案 1 :(得分:2)

之前我遇到过同样的问题,我发现当没有故事板或其他东西丢失时,应用程序甚至都没有启动。我建议你设置一个新项目,添加你的状态条码,然后做两件事:

  • 将“Application is UIElement(Agent)”键添加到info.plist文件并将其设置为true
  • 转到故事板,选择窗口控制器并在属性检查器右侧取消“初始视图控制器”

如果您对状态栏项目有任何其他疑问,我很乐意为您提供帮助