【问题标题】:Minimal Cocoa/Swift menu bar app doesn't want to run最小的 Cocoa/Swift 菜单栏应用程序不想运行
【发布时间】:2015-08-29 20:52:55
【问题描述】:

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

【问题讨论】:

    标签: xcode swift cocoa


    【解决方案1】:

    你需要有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

    【讨论】:

    • 谢谢 -- 我不明白为什么 OPs 代码不起作用,但我可以确认它工作正常!
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多