Nisba
Nisba

Reputation: 3448

Key pressed event in NSTextView (macOS)

I am writing a code in Swift for macOS (so I am using AppKit, not UIKit). I have a NSTextView which is not editable. I want to emulate a kind of terminal. The code below understands when the user press RETURN and prints ">>\n". I would like to be able to be notified when the user presses any key, in order to write the corresponding key. For instance if the user will press BACKSPACE, I will delete one character from the NSTextView unless the ">>" is going to be deleted.

This is the code. import Cocoa

class ViewController: NSViewController {
    @IBOutlet var console: Console!

    override func viewDidLoad() {
        super.viewDidLoad()

        console.parent = self
        }

        func newLine() {
            let textStorage = console.textStorage
            if(textStorage != nil) {
                let myString = "\n>>"
                let myAttribute = [ NSForegroundColorAttributeName: NSColor.greenColor(), NSFontAttributeName: NSFont(name: "Menlo Regular", size: 13.0)! ]
                let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)

                textStorage!.appendAttributedString(myAttrString)
                let length = console.string!.characters.count

                console.setSelectedRange(NSRange(location: length,length: 0))
                console.scrollRangeToVisible(NSRange(location: length,length: 0))
            }
        }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

class Console : NSTextView {
    var parent: ViewController?
    override func insertNewline(sender: AnyObject?) {
        parent!.newLine()
    }

    override func controlTextDidBeginEditing(obj: NSNotification) {
        NSLog("wow") //unfortunately this method is never called, even setting the NSTextView as Editable
    }
}

Related question: How to capture user input in real time in NSTextField?

Upvotes: 2

Views: 750

Answers (1)

1024jp
1024jp

Reputation: 2208

You can override NSTextView's keyDown(with event: NSEvent) for general key press. And check event.charactersIgnoringModifiers or event.modifierFlags to know which key was pressed.

Upvotes: 3

Related Questions