Swift中StatusItem的操作无法正常工作

4

我是Swift的新手,想在MacOS上创建一个简单的状态栏应用程序。为了保持代码整洁,我创建了一个名为App的子类,该子类负责创建状态栏项。接着在AppDelegate.swift文件的applicationDidFinishLaunching函数中创建了这个类实例。

但是,当我点击状态图标时,控制台没有输出任何内容。但是,如果我将代码复制到AppDelegate文件中,它就可以正常工作。有人知道我做错了什么以及为什么在子类中没有起作用吗?

下面是我的App类的代码:

import Cocoa

class App: NSObject {

    let menuBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

    override init() {
        print("created app instance");

        if let button = menuBarItem.button {
            button.image = NSImage(named: NSImage.Name("StatusBarButtonImage"))
            button.action = #selector(test(_:))
        }
    }

    @objc func test(_ sender: Any?) {
        print("button was pressed")
    }
}

以及AppDelegate:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var appInstance: App!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        appInstance = App()
    }

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

我猜这是因为你正在尝试在init中以编程方式设置menuBarItem.button。此时它尚未被创建,因此您不会进入if let button = menuBarItem.button情况。 我建议您覆盖viewDidMoveToWindow()方法: override func viewDidMoveToWindow(){ //此时您的按钮不为nil} - Olympiloutre
1个回答

7

如果按钮出现了,但是单击它时没有任何反应,那么我认为您需要确保将按钮的target设置为您的App实例。例如:

button.target = self

否则,该操作只会在响应者链中进行跟进。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接