因此,我是Swift的新手,想在MacOS上创建一个简单的示例状态栏应用程序。为了保持整洁,我创建了一个子类App,该子类正在创建状态项。然后在applicationDidFinishLaunchingAppDelegate.swift函数中创建此类。
但是当我按下状态图标时,控制台上什么也不会打印。但是,如果我将代码复制到AppDelegate文件中,则可以正常工作。有人知道我在做什么错吗,为什么它不能在子类中工作?
这是我自己的班级的代码:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
和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
}
}
Run Code Online (Sandbox Code Playgroud)
如果该按钮显示出来,但单击时什么也没有发生,则对我来说,您需要确保将按钮设置target为App实例。例如:
button.target = self
Run Code Online (Sandbox Code Playgroud)
否则,仅在响应者链中跟踪该操作。
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |