This might be an easy question, but I am new to Swift and do not know for which terms to google for.
For a menu bar application, I have implemented a custom function called doSomething that works just fine when it is bound to some button:
Class MainViewController:
{
@IBAction func doSomething(sender: NSButton)
{
// Do something when NSButton is pressed
}
}
However, I need to distinguish between left- and right click on the button, which in my case is a NSStatusBarButton. Following the suggestion from this answer, I have written the following into my AppDelegate.swift:
@NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
var mainViewController: MainViewController?
func applicationDidFinishLaunching(notification: NSNotification)
{
if let button = statusItem.button
{
button.action = #selector(customClickAction)
button.sendActionOn(Int(NSEventMask.RightMouseDownMask.rawValue | NSEventMask.LeftMouseDownMask.rawValue))
}
}
func customClickAction(sender: NSButton)
{
let event:NSEvent! = NSApp.currentEvent!
if (event.type == NSEventType.RightMouseDown)
{
print("Right mouse button down")
}
else if (event.type == NSEventType.LeftMouseDown)
{
print("Left mouse button down")
mainViewController?.doSomething(_:) // THIS DOES NOT WORK
}
}
}
The above code snippet gives me the error message 'Expression resolves to an unused function' in XCode. I cannot figure out how to properly call the function doSomething from the MainViewController class within the customClickAction function, or equivalently, how to redirect the action of the statusItem.button via customClickAction to doSomething. I apologize if this question might seem too trivial for the Swift experts, but I am really in despair trying to figure this one out.
EDIT:
If the function customClickAction was not existing, I would simply write button.action = #selector(mainViewController?.show(_:)) in applicationDidFinishLaunching to call the function and everything works. However, part of my problem is that doing the same in my custom function would overwrite the binding once the left mouse button has been pressed for the first time.