【问题标题】:Swift: Refresh menu bar on clickSwift:单击时刷新菜单栏
【发布时间】:2014-11-30 15:37:09
【问题描述】:

我正在为 Mac OS X 制作状态栏应用程序,但是我只希望在单击状态栏项目时刷新它。

这是我的代码:

class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet weak var window: NSWindow!
    @IBOutlet var menu: NSMenu!


    var statusItem: NSStatusItem!;

    @IBAction func quit(sender: AnyObject) {
        NSApplication.sharedApplication().terminate(nil)
    }

    func Refresh(){
        NSLog("Refresh")
    }

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
        statusItem.title = "Battery Infomation"
        statusItem.menu = self.menu
        statusItem.highlightMode = true
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }


}

如果有人可以帮助我做到这一点,将不胜感激。

【问题讨论】:

    标签: macos swift statusbar


    【解决方案1】:

    您正在寻找的是validateMenuItem:。这是一个检查菜单是否应该启用或禁用的地方。因此,它会在每次菜单出现之前被调用。您可以使用它来更新标题以反映电池状态。

    override func validateMenuItem(menuItem: NSMenuItem) -> Bool {
        if(menuItem.action == Selector("batteryStatus:")) {
            NSLog("refresh!");
            let now = NSDate()
            menuItem.title = String(format:"%f", now.timeIntervalSince1970);
            return true;
        }
        return true;
    }
    
    @IBAction func batteryStatus(sender: NSObject) {
    
    }
    

    【讨论】:

    • 感谢@Bird 的回答,但是您知道如何快速执行此操作,因为这是我使用的语言吗?如果它有帮助,我已经更新了我正在使用的代码,以使我的自我更清晰!
    • @aPyDeveloper 从来没有想过将 obj-c 转换为 swift 是个问题。给你!
    • 谢谢@Bird。我要求您转换它的唯一原因是因为我是 xcode 的新手。
    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 2016-10-28
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多