Oscar Franco
Oscar Franco

Reputation: 6220

Swift NSTextField, execute on Cmd + Enter

So, just some context, I have implemented a wrapping SwiftUI View for a NSTextView, everything is working more or less fine, but I would like to add a listener for when the Cmd + Enter combo is pressed, so far I got this:

class Coordinator: NSObject, NSTextViewDelegate {
    var parent: NSTextViewWrapper

    init(_ parent: NSTextViewWrapper) {
        self.parent = parent
    }

    func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        if commandSelector == #selector(NSResponder.insertNewLine(_:)) {
            let event = NSApp.currentEvent
            // if event?.modifierFlags != NSEvent.ModifierFlags.command {
            // Here I would like to trigger some action when the user is done editing the text field and wants to commit the result
            //   return true
            // }
                return false
            }
            return false
        }

For the life of me I cannot figure out how to do this.

Upvotes: 4

Views: 430

Answers (1)

P. A. Monsaille
P. A. Monsaille

Reputation: 207

Nice. With @LeoDabus input there's really not much to change:

func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if let event: NSEvent = NSApp.currentEvent {
        if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == [.command] && event.keyCode == 36 {
            print("caught [⌘ + ⏎]")
        }
        return true
    }
    return false
}

And thus conclude fruitless hours with an obscure one-liner from the comment section. 🎉

Upvotes: 5

Related Questions