Reputation: 7960
An NSTextField
can connect to an IBAction
and will call it when the user hits the enter key.
How can I perform an action with an NSTextView
when the user presses Command-Enter (Or Option-Enter, etc)?
Reading the documentation leads me to think it's something to do with doCommandBySelector:
but I can't find any examples.
Upvotes: 2
Views: 1110
Reputation: 236260
You can override keyDown event and check if return key code == 36 (return key) or and key code == 76 (enter key) and modifierFlags = CommandKeyMask. Try as follow:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var textView: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
self.keyDown(with: $0)
return $0
}
}
override func keyDown(with event: NSEvent) {
super.keyDown(with: event)
if event.keyCode == 36 && event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command {
print("command-return pressed")
}
if event.keyCode == 76 && event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command {
print("command-enter pressed")
}
}
}
Upvotes: 3