Objective-c – Best way to capture key events in NSTextView

cocoaeventsobjective c

I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help?

Best Answer

Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function.

So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this:

- (void)keyUp:(NSEvent *)theEvent

Note that this is an inherited NSResponder method, not a NSTextView method.