Search code examples
swiftmacoscocoaappkitfoundation

Send command shortcut to NSTextView's next responder


I have an MacOS app that listens to key events by implementing NSWindow.keyDown(with event:). I use this to enable shortcuts like ⌘ n to create a new item. This works well except when there is an NSTextView that is the first responder. In that case, the text view will swallow the event and my keyDown function will not get called. How do I prevent this and have the textview send events to the next responder (eventually my NSWindow)?


Solution

  • You can subclass NSTextView override keyDown method and call next responder:

    import Cocoa
    
    class TextView: NSTextView {
        override func draw(_ dirtyRect: NSRect) {
            super.draw(dirtyRect)
        }
    
        override func keyDown(with event: NSEvent) {
            super.keyDown(with: event)
            nextResponder?.keyDown(with: event)
        }
    }