Search code examples
swiftcocoa

trying to get this event through my function in swift XCode


I'm looking to pass a event.keycode event through a function

I use this code:

    NSEvent.addLocalMonitorForEvents(matching: .keyDown) { //monitors which keys are pressed down.
        self.keyDown(with: $0)
        return $0

override  func keyDown(with event: NSEvent) { // Detects which keys are being hit.
                
        
       keydownlook().keyPressed("here")  <-- calling a function that is in another class

        
  }

I need to pass the event not just the result, where it says here. is there any easy way to do this?


Solution

  • For instance, you can do this using closures:

    class Test {
        var keyEventHandler: ((NSEvent) -> Void)?
    
        func keyPressed(event: NSEvent) {
            keyEventHandler?(event)
        }
    }
    

    Usage:

    let test = Test()
    
    test.keyEventHandler = { event in
        print(event)
    }