首页 > 解决方案 > 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)?

标签: swiftmacoscocoaappkitfoundation

解决方案


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)
    }
}

推荐阅读